我需要使用 data.table 加速代码。我被困在如何引用从向量中索引的变量上。
数据:
df <- data.frame(
id=c(1,1,1,2,2,2,3,3,3),
year=as.character(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()
dtplyr 代码:
cols <- c("dv1", "dv2")
test <- function(data, columns, group) {
for(i in seq_along(columns)) {
sub1 <- df %>%
select("id", columns[i], group) %>%
group_by(.data[[group]]) %>%
summarise(mean=mean(.data[[columns[i]]], na.rm=T), sd=sd(.data[[columns[i]]], na.rm=T)) %>%
ungroup() %>%
as_tibble()
print(sub1)
}
}
数据表尝试:
test <- function(data, columns, group) {
for(i in seq_along(columns)) {
sub1 <- df %>%
.[, .(id, columns[i], group)] %>%
.[, .(mean(.data[[columns[i]]], na.rm=T), sd=sd(.data[[columns[i]]], na.rm=T)), by=.data[[group]]] %>%
as_tibble()
print(sub1)
}
}
test(data=df, columns=cols, group="year")
这适用于单个变量:
df %>%
.[, .(id, dv1, year)] %>%
.[, .(mean(dv1, na.rm=T), sd=sd(dv1, na.rm=T)), by=year] %>%
as_tibble()