使用r对每行进行条件计数
我尝试了各种解决办法,但我的问题仍然存在。我有一个大的df(20rows*400cols)-对于每一行,我想计算有多少列的值大于16 第一列是factor,其余列是整数 我的df:使用r对每行进行条件计数,r,dataframe,dplyr,count,R,Dataframe,Dplyr,Count,我尝试了各种解决办法,但我的问题仍然存在。我有一个大的df(20rows*400cols)-对于每一行,我想计算有多少列的值大于16 第一列是factor,其余列是整数 我的df: col1 col2 col3 col4 abc 2 16 17 def 4 2 4 geh 50 60 73 所需输出应为: col1 col2 col3 col4 count abc 2 16 17 1 def 4 2
col1 col2 col3 col4
abc 2 16 17
def 4 2 4
geh 50 60 73
所需输出应为:
col1 col2 col3 col4 count
abc 2 16 17 1
def 4 2 4 0
geh 50 60 73 3
我尝试了
df$16以上)
但是在count
列中我得到了NA
。我们可能需要NA.rm
来处理NA
元素作为/这里有另一个使用crossprod
df$count <- c(crossprod(rep(1, ncol(df[-1])), t(df[-1] > 16)))
df <- type.convert(df, as.is = TRUE)
str(df)
df[-1] <- lapply(df[-1], function(x) as.numeric(as.character(x)))
df$count <- c(crossprod(rep(1, ncol(df[-1])), t(df[-1] > 16)))
col1 col2 col3 col4 count
1 abc 2 16 17 1
2 def 4 2 4 0
3 geh 50 60 73 3