r - 总结 NA,按组计数
问题描述
我有这个用于测试的数据框:
test_df <- structure(list(plant_sp = c("plant_1", "plant_1", "plant_2", "plant_2", "plant_3",
"plant_3", "plant_3", "plant_3", "plant_3", "plant_4",
"plant_4", "plant_4", "plant_4", "plant_4", "plant_4",
"plant_5", "plant_5", "plant_5", "plant_5", "plant_5"),
sp_rich = c(1, 1, NA, 1, NA,
1, 0, 0, NA, 0,
0, 1, 0, 0, 1,
0, NA, NA, 0,NA)),
row.names = c(NA, -20L), class = "data.frame",
.Names = c("plant_sp", "sp_rich"))
我想创建一个新的数据框,其中包含从这些数据中提取的数据:
表示每组中的计数和 NA (例如,在组 plant_1 中,组中只有 2 个“1”和 0 个“NA”
你能帮助我吗?谢谢伊多
解决方案
这应该工作
library(dplyr)
test_df %>%
group_by(plant_sp) %>%
summarize(count = sum(sp_rich > 0 & !is.na(sp_rich)),
miss = sum(is.na(sp_rich)))
# A tibble: 5 x 3
plant_sp count miss
<chr> <int> <int>
1 plant_1 2 0
2 plant_2 1 1
3 plant_3 1 2
4 plant_4 2 0
5 plant_5 0 3
推荐阅读
- javascript - 使用jquery blur时如何防止空输入字段被认为是错误的
- double - USQL 转义引号
- java - 如何使用 Google 帐户凭据 OAuth2 (Java) 从 Google 注销
- c# - 如何使用 azure webjob 每 12 点大规模发送电子邮件报告?
- mysql - 使用 OR 条件的 MySQL 连接性能问题
- javascript - 排列/格式化html和js代码
- php - 如何使用邻接树方法在二叉树下获得空闲槽
- python - 在 Google App Engine 中使用 Python 的私有存储库
- java - 批处理管道上的不同操作
- opengl-es - 使用“平面”着色器接口变量会导致性能大幅下降