[R] Summing certain values within columns that satisfy a certain condition

Kate Ignatius kate.ignatius at gmail.com
Thu Feb 26 21:23:48 CET 2015


Hi,

Supposed I had a data frame like so:

A B C D
0 1 0 7
0 2 0 7
0 3 0 7
0 4 0 7
0 1 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 1 5
0 5 1 5
0 4 1 5
0 8 4 7
0 0 3 0
0 0 3 4
0 0 3 4
0 0 0 5
0 2 0 6
0 0 4 0
0 0 4 0
0 0 4 0

For each row, I want to count how many max column values appear to
adventurely get the following outcome, while ignoring zeros and N/As:

A B C D Sum
0 1 0 7 1
0 2 0 7 1
0 3 0 7 1
0 4 0 7 1
0 1 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 1 5 0
0 5 1 5 0
0 4 1 5 0
0 8 4 7 3
0 0 3 0 0
0 0 3 4 0
0 0 3 4 0
0 0 0 5 0
0 2 0 6 0
0 0 4 0 1
0 0 4 0 1
0 0 4 0 1

I've used the following code but it doesn't seem to work (my sum
column column is all 1s):

(apply(df,1, function(x)  (sum(x %in% c(pmax(x))))))

Is this code too simple?

Thanks!

K.



More information about the R-help mailing list