我是一名使用 R 的行为生态学家。我正在尝试计算多个列中的非零元素。通常,当我这样做时,我已经成功地将 colSums 与 !=0 运算符结合使用,正如此处和其他地方的许多帖子中所建议的那样,即(Count the number of non-zero elements of each column)。
然而,在这种特殊情况下,我真的更喜欢使用管道——因为这只是构建更大数据框的一个步骤——而且我似乎无法获得带有 !=0 的 colSums 来很好地处理管道。有没有办法让它工作,或者是否有更优雅的替代方法来计算生活在 tidy-verse 某处的列中的非零值?
我在下面放了一些示例代码来演示。非常感谢!
'''
#make example dataframe
example<- as.data.frame(matrix(sample(c(0,0,0,100),size=70,replace=T),ncol=7))
example<-cbind(Indentifier1="character a",Indentifier2="character b", example)
example
#works great but isn't piping friendly:
colSums(example[-c(1:2)] !=0)
#Runs but because it lacks the !=0 operator it gives sums not counts of non-zero elements, can't figure out how to employ !=0:
example %>% select(-c(1:2)) %>% colSums()
#gives me counts of all values, not sure how to call just non-zero values:
example %>% summarise(across(where(is.numeric), length))
'''
最佳答案
示例 %>% summarise(across(where(is.numeric), ~sum(. != 0)))
关于r - 统计每列非零元素的个数——管道友好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71519816/