Danny David Leybzon Danny David Leybzon - 2 months ago 5
R Question

Number of column values greater than 0 for given row?

I have a dataframe which looks like:

col1 col2 col3
0 0 .4
.3 1 0
0 0 .8


I'd like to create a new column which counts the number of column values greater than 0 in the other three rows:

col1 col2 col3 col4
0 0 .4 1
.3 1 0 2
0 0 .8 1

Answer

You just need to use the apply function:

## Example Data
dd = data.frame(col1 = c(0, .3, 0), col2=c(0, 1, 0),
                        col3=c(0.4, 0, 0.8))
apply(dd, 1, function(i) sum(i > 0))

So to add this too your existing data frame:

dd$col4 =  apply(dd, 1, function(i) sum(i > 0))

Alternatively, we could convert the data frame to logical values then use rowSums

rowSums(dd > 0)
Comments