我想定义一个函数,该函数接受一个data.frame和一个列名,并以转换后的列(例如,将其转换为小写)的形式返回data.frame。 如果事先知道列名,则很简单:
diamonds %>% mutate(cut = tolower(cut))
如何定义函数foo
,例如:
col <- "cut"
foo(diamonds, col)
是否有同样的行为? (因为我想保留data.table
将其转换为延迟评估的SQL调用的能力,所以不寻找基本的R或dplyr
答案)。
如果我只是想使用以下功能来工作:foo(diamonds, cut)
,则只需要enquo
和!!
foo <- function(df, col){
x <- enquo(col)
mutate(df, !!x := tolower(!!x))
}
如果我想用引号foo(diamonds, "cut")
加上列名,则添加ensym
就足够了:
foo <- function(df, col){
col <- ensym(col)
x <- enquo(col)
mutate(df, !!x := tolower(!!x))
}
,但是在给变量提供参数时失败:
col <- "cut"
foo(diamonds, col)
Error in ~col : object 'col' not found
我缺少什么可以评估变量的信息?
答案 0 :(得分:7)
您还可以通过使用mutate_at()
完全避免在这里进行整洁的评估。
library(tidyverse)
(x <- tibble(
num = 1:3,
month = month.abb[num]
))
#> # A tibble: 3 x 2
#> num month
#> <int> <chr>
#> 1 1 Jan
#> 2 2 Feb
#> 3 3 Mar
x %>%
mutate(month = tolower(month))
#> # A tibble: 3 x 2
#> num month
#> <int> <chr>
#> 1 1 jan
#> 2 2 feb
#> 3 3 mar
foo <- function(df, col) {
mutate_at(df, .vars = col, .funs = tolower)
}
foo(x, "month")
#> # A tibble: 3 x 2
#> num month
#> <int> <chr>
#> 1 1 jan
#> 2 2 feb
#> 3 3 mar
this <- "month"
foo(x, this)
#> # A tibble: 3 x 2
#> num month
#> <int> <chr>
#> 1 1 jan
#> 2 2 feb
#> 3 3 mar
由reprex package(v0.2.1.9000)于2019-03-09创建
答案 1 :(得分:2)
library(tidyverse)
col <- "cut"
foo <- function(df, col) {
df %>%
mutate(!!sym(col) := tolower(!!sym(col)))
}
foo(diamonds, col)
答案 2 :(得分:0)
回到您的原始示例,只需使用ensym()
将文本参数转换为符号,在这种情况下就无需四舍五入了。
library(ggplot2)
col <- "cut"
foo <- function(df, col){
col <- rlang::sym(col)
dplyr::mutate(df, !!col := tolower(!!col))
}
foo(diamonds, col)
#> # A tibble: 53,940 x 10
#> carat cut color clarity depth table price x y z
#> <dbl> <chr> <ord> <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#> 1 0.23 ideal E SI2 61.5 55 326 3.95 3.98 2.43
#> 2 0.21 premium E SI1 59.8 61 326 3.89 3.84 2.31
#> 3 0.23 good E VS1 56.9 65 327 4.05 4.07 2.31
#> 4 0.290 premium I VS2 62.4 58 334 4.2 4.23 2.63
#> 5 0.31 good J SI2 63.3 58 335 4.34 4.35 2.75
#> 6 0.24 very good J VVS2 62.8 57 336 3.94 3.96 2.48
#> 7 0.24 very good I VVS1 62.3 57 336 3.95 3.98 2.47
#> 8 0.26 very good H SI1 61.9 55 337 4.07 4.11 2.53
#> 9 0.22 fair E VS2 65.1 61 337 3.87 3.78 2.49
#> 10 0.23 very good H VS1 59.4 61 338 4 4.05 2.39
#> # … with 53,930 more rows
由reprex package(v0.2.1)于2019-03-11创建