【发布时间】:2020-05-04 21:00:04
【问题描述】:
我有一个包含数值变量和分组变量的数据集,并且想要计算组均值。有些组是空的,即有一些因子水平没有出现在数据中。在计算分组平均值时,我希望将这些空组与非空组一起列出。使用 base R 很容易实现:
# Create an example of a data frame where variable1 is numeric and variable2 is a
# factor with three levels, two of which appear in the data:
df <- data.frame(variable1 = c(1,2,3,4), variable2 = factor(c("A","B","A","B")))
levels(df$variable2) <- c(levels(df$variable2), "C")
# Base R
tapply(df$variable1, df$variable2, mean)
渲染输出
A B C
2 3 NA
这就是我要找的。p>
但是,由于各种原因,我需要使用 dplyr 或 data.table 来代替。问题是两者都跳过了摘要中的空白级别:
library(dplyr)
df %>% group_by(variable2) %>%
summarise(var1Mean = mean(variable1))
产量
# A tibble: 2 x 2
variable2 var1Mean
<fct> <dbl>
1 A 2
2 B 3
和
library(data.table)
df <- as.data.table(df)
df[, mean(variable1), variable2]
产量
variable2 V1
1: A 2
2: B 3
有没有办法让这些包中的任何一个在摘要中包含空组?
【问题讨论】:
标签: r dplyr data.table