[R] ifelse on a series of rows for multiple criteria

Steve Murray smurray444 at hotmail.com
Fri Feb 5 16:48:09 CET 2010


Dear all,

I am attempting to perform a calculation which counts the number of positive (or negative) values based on the sample mean (on a per-row basis). If the mean is>0 then only positive values should be counted, and if the mean is <0 then only negative values should be counted. In cases where the mean is equal to zero, the value -99999 should be returned.

The following is an example of the data frame I'm working on (all values are of class 'numeric').

> head(combdframe)
         V1       V2        V3         V4       V5        V6
1 -328.0999 3404.038  791.7602  211.23932 513.0479 -1178.079
2 -383.4249 3207.306  808.7268  141.20352 424.2388 -1164.402
3 -295.9050 2930.754  918.1146   11.74804 464.2448 -1133.109
4 -326.8606 2703.638 1052.2824 -104.17344 246.2851 -1103.887
5 -296.7194 2663.987 1202.7648  -87.15331 255.1338 -1090.147
6 -227.1772 2619.096 1343.1529  -75.89626 381.6089 -1064.733


The mean of the first row is 571 and therefore a count of the positive values should be returned for this row (=4). *If* the mean was -571, then a count of the negative values would be returned (=2).
If the 7th row was composed of values 1.5, -1.5, 2.5, -2.5, 0  and 0 (i.e. the mean = 0), then -99999 should be returned for this row.

I've attempted to construct this code as follows:

direction_func <- function(combdframe) {
    ifelse(mean(i> 0), sum(i> 0), ifelse(mean(i < 0), sum(i < 0), -99999))
    }
    
for (i in nrow(combdframe)) {

direction <- apply(combdframe[i,],1, direction_func)

}


...but this, and varients on this, result in a bit of a mess!


Any guidance on how to perform this (whether it be a correction of the above or a whole new approach) would be very much appreciated.

Many thanks,

Steve
 		 	   		  
_________________________________________________________________
We want to hear all your funny, exciting and crazy Hotmail stories. Tell us now



More information about the R-help mailing list