【问题标题】:R user defined functions: new data frame name as function parameterR用户定义函数:新数据框名称作为函数参数
【发布时间】:2019-02-08 19:26:31
【问题描述】:

我在编写用户定义的函数来操作 R 中的数据框时遇到了一个问题。我想编写带有 2 个参数的函数:输入数据框的名称和将在其中创建的数据框的名称功能。以下是使用 mtcars 数据集的示例:

subset_high_hp <- function(full_table, only_highHP) {
  only_highHP <<- full_table %>% 
    filter(hp > 200)

}

subset_high_hp(mtcars, mtcars_highhp)

subset_high_hp 现在创建一个名为 only_highHP 的数据框,而不是所需的 mtcars_highhp。我知道这是一个非常基本的问题,但我是 R 新手,并且真的很难找到正确的文档。谁能指出我正确的方向?

【问题讨论】:

  • 为什么不简单地将函数的输出分配给您想要的名称呢? (例如only_highHP &lt;- subset_high_hp(mtcars))。我的意思是为什么将名称作为函数参数?这到底是什么意思?
  • 这个函数将在另一个通过数据框列表索引的函数中调用,所以我需要能够同时索引新数据框名称的列表并执行除子集之外的各种其他任务,但是如果我以不同的方式构建代码,这将起作用。谢谢!

标签: r parameter-passing user-defined-functions


【解决方案1】:

我认为你可以使用assign 来做这个技巧:

subset_high_hp <- function(full_table, df_name) {
  sub_df <- full_table %>% 
    filter(hp > 200)

  assign(x = df_name, value = sub_df, envir = globalenv())
}

subset_high_hp(full_table = mtcars, df_name = "mtcars_highhp")
mtcars_highhp

   mpg cyl disp  hp drat    wt  qsec vs am gear carb
1 14.3   8  360 245 3.21 3.570 15.84  0  0    3    4
2 10.4   8  472 205 2.93 5.250 17.98  0  0    3    4
3 10.4   8  460 215 3.00 5.424 17.82  0  0    3    4
4 14.7   8  440 230 3.23 5.345 17.42  0  0    3    4
5 13.3   8  350 245 3.73 3.840 15.41  0  0    3    4
6 15.8   8  351 264 4.22 3.170 14.50  0  1    5    4
7 15.0   8  301 335 3.54 3.570 14.60  0  1    5    8

【讨论】: