Count number of columns by a condition (>) for each row

我只是一个虾纸丫 提交于 2019-11-27 04:45:14

This will give you the vector you are looking for:

rowSums(data > 30)

It will work whether data is a matrix or a data.frame. Also, it uses vectorized functions, hence is a preferred approach over using apply which is little more than a (slow) for loop.

If data is a data.frame, you can add the result as a column by doing:

data$yr.above <- rowSums(data > 30)

or if data is a matrix:

data <- cbind(data, yr.above = rowSums(data > 30))

You can also create a whole new data.frame:

data.frame(yr.above = rowSums(data > 30))

or a whole new matrix:

cbind(yr.above = rowSums(data > 30))

The third argument of apply needs to be a function. Also, you can count logical trues with sum.

apply(data, 1, function(x)sum(x > 30))

We can also do with Reduce and + (assuming there are no NA elements)

 Reduce(`+`, lapply(as.data.frame(data), `>`, 30))

This should be efficient as we are not converting to a matrix.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!