![](/img/trans.png)
[英]Can mutate_at name a variable according to a wrapped function name? (dplyr + rlang question)
[英]understanding rlang: mutate with variable col name and variable column
我想定義一個帶有data.frame和列名的函數,並返回data.frame,並將該列轉換為(例如小寫)。 當列名提前知道時,這很簡單:
diamonds %>% mutate(cut = tolower(cut))
如何定義函數foo
,例如:
col <- "cut"
foo(diamonds, col)
做同樣的行為嗎? (不尋找基本R或data.table
答案,因為我想保留dplyr
將其轉換為懶惰評估的SQL調用的能力)。
如果我只是想讓我的功能使用: 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
我錯過了什么可以評估變量?
您還可以使用mutate_at()
完全避免整理eval。
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包創建於2019-03-09(v0.2.1.9000)
library(tidyverse)
col <- "cut"
foo <- function(df, col) {
df %>%
mutate(!!sym(col) := tolower(!!sym(col)))
}
foo(diamonds, col)
回到原始示例,只需使用ensym()
將文本參數轉換為符號,在這種情況下不需要quosure。
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包創建於2019-03-11(v0.2.1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.