首页 > 解决方案 > 总结 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"))

我想创建一个新的数据框,其中包含从这些数据中提取的数据:

我需要的df

表示每组中的计数和 NA (例如,在组 plant_1 中,组中只有 2 个“1”和 0 个“NA”

你能帮助我吗?谢谢伊多

标签: rdplyrtidyverseplyr

解决方案


这应该工作

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

推荐阅读