我们如何计算满足某些条件的列数。
df <- data.frame(id=c(1,2,3,4),v1=c(0.2,0.4,0.6,0.9),
v2=c(0.1,0.2,0.6,0.1),v3=c(0.1,0.4,0.6,0.1))
count<-function(x){dplyr::count(x>=0.5)}
df$count<-apply(x = df[,c(2:4)], MARGIN = 1, FUN =count, na.rm = TRUE)
这不起作用.....
应该是
df$count<-c(0,0,3,1)
答案 0 :(得分:2)
您可以使用rowSums
来计算df[-1]>=0.5
的条件:
rowSums(df[-1]>=0.5)
#[1] 0 0 3 1
答案 1 :(得分:1)
带有Reduce
Reduce(`+`, lapply(df[-1], `>=`, 0.5))
#[1] 0 0 3 1