[R] Counting by rows based on multiple criteria
jim holtman
jholtman at gmail.com
Mon Feb 8 13:11:02 CET 2010
Will this do it for you:
> x <- matrix(sample(c(-1,0,1), 6000, TRUE), ncol=6)
> # compute the occurances
> gt0 <- rowSums(x > 0)
> lt0 <- rowSums(x < 0)
> eq0 <- rowSums(x == 0)
> x <- cbind(x, result=ifelse(eq0 == 6, -9999,
+ ifelse(gt0 > lt0, gt0,
+ ifelse(gt0 == lt0, 0, -lt0))))
> head(x,20)
result
[1,] 1 -1 0 -1 0 0 -2
[2,] -1 1 0 1 -1 1 3
[3,] -1 0 1 1 1 -1 3
[4,] -1 1 1 0 -1 0 0
[5,] 1 -1 -1 0 1 -1 -3
[6,] 1 0 1 0 0 0 2
[7,] 1 -1 1 1 1 -1 4
[8,] 1 -1 0 1 -1 1 3
[9,] 0 -1 1 -1 0 -1 -3
[10,] 1 0 -1 0 -1 0 -2
[11,] -1 1 1 1 1 -1 4
[12,] 0 0 0 0 1 1 2
[13,] 0 0 1 1 0 0 2
[14,] 1 0 0 -1 0 -1 -2
[15,] -1 0 0 0 0 1 0
[16,] 1 0 0 0 1 0 2
[17,] -1 -1 1 -1 0 0 -3
[18,] 1 1 1 0 0 -1 3
[19,] 0 1 -1 1 -1 1 3
[20,] 1 -1 -1 0 1 0 0
>
>
>
On Mon, Feb 8, 2010 at 6:54 AM, Steve Murray <smurray444 at hotmail.com> wrote:
>
> Dear all,
>
> I have a data frame of 6 columns and ~60000 rows which I hope to perform the following calculation on.
>
> For each row, I wish to determine whether there are a greater number of positive or negative numbers. Then, if there are more positive numbers in the row, count how many occur - but if there are more negative numbers in the row, count them instead and insert a minus symbol before (e..g -4, to denote that this was determined on negative numbers).
>
> If the number of positive and negative numbers in a given row are equal, then return a zero for that row.
>
> Finally, if all values in a row are zero (i.e. neither positve or negative) then return -99999.
>
>
> I've had a go at this myself for some considerable time, trying the use of an 'apply' (by rows) function, but seem unable to successfully achieve the above.
>
> Any help would be very gratefully received.
>
> Many thanks,
>
> Steve
>
>
> _________________________________________________________________
> Do you have a story that started on Hotmail? 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.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem that you are trying to solve?
More information about the R-help
mailing list