4

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
Danny David Leybzon
  • 670
  • 1
  • 9
  • 21

2 Answers2

3

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)
csgillespie
  • 59,189
  • 14
  • 150
  • 185
0

Another option is Reduce with + after looping over the columns to create a list of logical vectors

dd$col4 <- Reduce(`+`, lapply(dd, `>`, 0))
dd
#  col1 col2 col3 col4
#1  0.0    0  0.4    1
#2  0.3    1  0.0    2
#3  0.0    0  0.8    1
akrun
  • 874,273
  • 37
  • 540
  • 662