sum if greater than in r

…衆ロ難τιáo~ 提交于 2019-12-01 20:58:56
#your data
DF <- as.data.frame(matrix(1:6, ncol = 2))
#turn into matrix
m <- as.matrix(DF)

#your threshold
thr <- c(3, 1, 7)

#compare
m >= thr
#        V1    V2
#[1,] FALSE  TRUE
#[2,]  TRUE  TRUE
#[3,] FALSE FALSE

#logical values get turned to 0/1 during arithmetics
#thus we can just multiply the matrix with the comparison
m * (m >= thr)
#     V1 V2
#[1,]  0  4
#[2,]  2  5
#[3,]  0  0

#and calculate the row sums
rowSums(m * (m >= thr))
#[1] 4 7 0
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!