首页 > 解决方案 > R用户定义函数:新数据框名称作为函数参数

问题描述

我在编写用户定义的函数来操作 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 新手,并且真的很难找到正确的文档。谁能指出我正确的方向?

标签: rparameter-passinguser-defined-functions

解决方案


我认为您可以使用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

推荐阅读