将列名称作为字符串传递给with

时间:2018-12-11 09:57:29

标签: r substitution evaluation

给出以下示例:

sort_by_column <- function(x = mtcars, col = "cyl") {
    col <- deparse(substitute(col))
    x[with(x, order(col)),]
}

sort_by_column(col = "cyl")

我想将列名作为字符串传递给with,如下所示:

sort_by_column(col = "cyl")

预期结果

mtcars[with(mtcars, order(cyl)),]

问题

"cyl"调用中,使cyl自变量显示为with

注释

  • 我不想修改x[with(x, order(col)),]语句
  • 我对dplyr::arrange解决方案
  • 不感兴趣

2 个答案:

答案 0 :(得分:2)

由于我们想用with来评估值,因此我们可以在此处使用get

sort_by_column <- function(x = mtcars, col = "cyl") {
    x[with(x, order(get(col))),]
}

sort_by_column(col = "cyl")

#                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
#Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
#Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
#Fiat 128            32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
#Honda Civic         30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
#Toyota Corolla      33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
#Toyota Corona       21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
#Fiat X1-9           27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
#Porsche 914-2       26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
#Lotus Europa        30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
#Volvo 142E          21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2
#Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#......

答案 1 :(得分:1)

在这种情况下,我们可以使用[[进行子集

sort_by_column <- function(x = mtcars, col = "cyl") {
    x[order(x[[col]]),]
   }

sort_by_column(col = "cyl")
#                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
#Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
#Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
#Fiat 128            32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
#Honda Civic         30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
#Toyota Corolla      33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
#Toyota Corona       21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
#Fiat X1-9           27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
#Porsche 914-2       26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
#Lotus Europa        30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
#Volvo 142E          21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2
#Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
#....