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

后端 未结 4 482
小蘑菇
小蘑菇 2020-11-27 19:37

I am trying to work out for each row of a matrix how many columns have values greater than a specified value. I am sorry that I am asking this simple question but I wasn\'t

4条回答
  •  情歌与酒
    2020-11-27 20:02

    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))
    

提交回复
热议问题