我有一个数据框df
。它看起来像:
xSample a b c
x 2 0 2
x1 3 0 0
x2 4 0 2
我有这段代码:
new_df <- as.data.frame(sapply(df[,-1], function(x) sum(as.numeric(x) > 0)))
我想浏览df
的每一列并计算样本数并将其放入new_df
,但前提是有&gt;每个样本A,B或C的0个计数... new_df
应如下所示:
NonZeroCounts
a 3
c 2
不保留b
行,因为它在每一行中都有0个计数。
在df
上运行上述功能后,输出为:
xSample NonZeroCounts
a 3
b 0
c 2
答案 0 :(得分:1)
另一种方法:
## Your data
df <- data.frame(a = c(2, 3, 4), b = c(0, 0, 0), c = c(2, 0, 2))
data.frame(NonZeroCounts=colSums(df!=0)[colSums(df!=0)!=0])
# NonZeroCounts
#a 3
#c 2
答案 1 :(得分:1)
首先,使用sapply
浏览相关列并获取非零值的数量。然后,使用colSums
仅对那些大于0
data.frame(NonZeroCounts = sapply(df1[-1], function(x)
sum(x>0))[colSums(df1[-1]) > 0])
# NonZeroCounts
#a 3
#c 2
数据强>
df1 = structure(list(xSample = c("x", "x1", "x2"), a = 2:4, b = c(0L,
0L, 0L), c = c(2L, 0L, 2L)), .Names = c("xSample", "a", "b",
"c"), class = "data.frame", row.names = c(NA, -3L))