尝试使用 dtplyr 按组汇总列时,分组似乎不起作用。由于 group 变量是我的函数的输入,因此我尝试使用 group_by_ 仅接收错误消息。
数据:
df <- data.frame(
id=c(1,1,1,2,2,2,3,3,3),
year=c(2014, 2015, 2016, 2015, 2015, 2016, NA, NA, 2016),
code=c(1,2,2, 1,2,3, 3,4,5),
dv1=1:9,
dv2=2:10
) %>% as.data.table()
cols <- c("dv1", "dv2")
> df
id year code dv1 d2
1: 1 2014 1 1 2
2: 1 2015 2 2 3
3: 1 2016 2 3 4
4: 2 2015 1 4 5
5: 2 2015 2 5 6
6: 2 2016 3 6 7
7: 3 NA 3 7 8
8: 3 NA 4 8 9
9: 3 2016 5 9 10
功能:
for(i in seq_along(columns)) {
sub1 <- df %>%
select("id", columns[i], group) %>%
group_by(group) %>%
summarise(mean=mean(.data[[columns[i]]], na.rm=T), sd=sd(.data[[columns[i]]], na.rm=T)) %>%
ungroup() %>%
as_tibble()
print(sub1)
}
}
test(data=df, columns=cols, group="year")
# A tibble: 1 x 3
group mean sd
<chr> <dbl> <dbl>
1 year 5 2.74
# A tibble: 1 x 3
group mean sd
<chr> <dbl> <dbl>
1 year 6 2.74