我希望能够更改数据表中包含分组变量的列的名称。我知道在不包装到函数中时如何做到这一点,但当我将分组数据表操作包装到函数中时,我无法确定如何同时设置名称以真正反映分组变量。
# load the data table library
library(data.table)
# load sample dataset for reproducible example
mtcars <- data.table(mtcars)
# define a function which would group given
# data table (1st parameter) by given column (2nd parameter)
grouping_function <- function(x, grouping1)
{
x[,
list(mean_disp = mean(disp),
mean_hp = mean(hp)),
.(get(grouping1))]
}
现在,如果我跑
grouping_function(mtcars, "cyl")
我得到的是
get,mean\u disp,mean\u hp
编辑
对于一个变量,正如罗曼·卢斯特里克(Roman Lustrik)的回答所建议的那样,修复似乎是向前迈进的。但当我有两个分组变量时,这种修复似乎不起作用:
# load the data table library
library(data.table)
# load sample dataset for reproducible example
mtcars <- data.table(mtcars)
# define a function which would group given
# data table (1st parameter) by given column (2nd parameter)
grouping_function <- function(x, grouping1, grouping2)
{
x[,
list(mean_disp = mean(disp),
mean_hp = mean(hp)),
.(get(grouping1), get(grouping2)]
}
在这里,仅使用by=list(grouping1,grouping2)或其他变体似乎失败了。