r - 统计每列非零元素的个数——管道友好

标签 r count pipe magrittr

我是一名使用 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/

相关文章:

r - 在 Ubuntu 上安装 R gsl 包

ruby - 如何使用 Pry 测试类似过滤器的 Ruby 脚本?

python - 操作系统错误: [Errno 2] No such file or directory running 2 pipes

r - 悬停格式仅适用于 $ 符号,不适用于其他货币?

python - 从非 R 脚本(例如 Python)访问/提取 R 帮助

r - Rmarkdown/knitr 中的 texreg

mysql - SQL - COUNT() 计数错误的数字

sql - 使用 GROUP BY 从多个表中选择

Ruby:如何计算一个字符串在另一个字符串中出现的次数?

在 fork() 和 exec() 之后创建管道