[R] ifelse on a series of rows for multiple criteria
David Winsemius
dwinsemius at comcast.net
Fri Feb 5 17:26:38 CET 2010
On Feb 5, 2010, at 10:48 AM, Steve Murray wrote:
>
> 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.
Try:
> (rowSums(combframe > 0))*(rowMeans(combframe)>0) +
(rowSums(combframe < 0))*(rowMeans(combframe) < 0) -
99999*(rowSums(combframe) == 0)
1 2 3 4 5 6 7
4 4 4 3 3 3 -99999
The equality holds here but I worry about "==" when working with
floating point numbers.
>
> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list