代码之家  ›  专栏  ›  技术社区  ›  ira

将数据表包装到函数中时如何设置分组变量列的名称

  •  0
  • ira  · 技术社区  · 7 年前

    我希望能够更改数据表中包含分组变量的列的名称。我知道在不包装到函数中时如何做到这一点,但当我将分组数据表操作包装到函数中时,我无法确定如何同时设置名称以真正反映分组变量。

    # 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)或其他变体似乎失败了。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Roman LuÅ¡trik    7 年前

    你不能具体说明一下吗 by

    grouping_function <- function(x, grouping1) {
      x[,
        list(mean_disp = mean(disp),
             mean_hp = mean(hp)),
        by = grouping1]
    }
    
    grouping_function(mtcars, "cyl")
    
       cyl mean_disp   mean_hp
    1:   6  183.3143 122.28571
    2:   4  105.1364  82.63636
    3:   8  353.1000 209.21429