假设我们有一个名为"myData"的数据框,其中有三列,分别为"Group", "Col1"和"Col2",我们想要按"Group"列分组,然后计算每个组中"Col1"和"Col2"列中空白单元格的数量。我们可以使用dplyr和tidyr包来完成这个任务。
首先,我们需要加载这些包:
library(dplyr)
library(tidyr)
接下来,我们可以使用dplyr的group_by函数按"Group"列中的值分组,然后使用summarise_all函数计算每个组中所有列中的汇总统计信息。我们可以将"is.na"函数作为summarise_all函数的参数,以计算每个列中空白单元格的数量。
myData %>%
group_by(Group) %>%
summarise_all(funs(sum(is.na(.))))
如果我们想将结果转换为更整洁的格式,我们可以使用tidyr的gather函数将列中的变量转换为行中的观测值。
myData %>%
group_by(Group) %>%
summarise_all(funs(sum(is.na(.)))) %>%
gather(key = "Column", value = "Count")
这将返回如下的数据框:
# A tibble: 6 x 3
Group Column Count
1 A Col1 2
2 A Col2 1
3 B Col1 1
4 B Col2 3
5 C Col1 3
6 C Col2 0