【问题标题】:How to use mutate inside a function with formulas instead of .dots and mutate_?如何在带有公式而不是 .dots 和 mutate_ 的函数中使用 mutate?
【发布时间】:2020-09-05 11:08:03
【问题描述】:

我曾经使用带有 .dots 参数的 mutate_ 使用用户提供的变量(字符串格式)和函数内部计算的变量(如 b下面的变量)如下:

require(dplyr)
f <- function(data, a)
{
    b <- "Sepal.Length"

    mutate_call <- list(new_1 = lazyeval::interp( ~ a*10, a=as.name(a)),
                        new_2 = lazyeval::interp( ~ b*10, b=as.name(b)) )
   
    data %>%
        as_tibble() %>%
        mutate_(.dots = mutate_call) %>%
        head() %>%
        print()
    
}

f(iris, "Sepal.Width")

但是,当转换到最近的 dplyr 版本时,这不再可能(除非我继续使用已弃用的版本 mutate_)。如何使用 mutate 而不是 mutate_ 获得与 f 相同的结果?

如果我能继续使用这些公式会容易得多。

【问题讨论】:

标签: r dplyr nse


【解决方案1】:

我的建议是从公式切换到表达式,然后使用 unquote-splice 运算符 !!! 和常规 mutate()

f <- function(data, a)
{
  # Convert strings to symbols
  a <- as.name(a)
  b <- as.name("Sepal.Length")
  
  # Use rlang::exprs to define the expressions
  # Use !! to replace a and b with the symbols stored inside them
  mutate_call <- rlang::exprs(new_1 = !!a*10, new_2 = !!b*10)

  data %>%
    as_tibble() %>%
    mutate(!!!mutate_call) %>%    # <-- !!! effectively "pastes" the expressions
    head() %>%
    print()
}

f(iris, "Sepal.Width")
# # A tibble: 6 x 7
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species new_1 new_2
#          <dbl>       <dbl>        <dbl>       <dbl> <fct>   <dbl> <dbl>
# 1          5.1         3.5          1.4         0.2 setosa     35    51
# 2          4.9         3            1.4         0.2 setosa     30    49
# 3          4.7         3.2          1.3         0.2 setosa     32    47
# 4          4.6         3.1          1.5         0.2 setosa     31    46

【讨论】:

    猜你喜欢
    • 2019-11-17
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 2018-12-29
    相关资源
    最近更新 更多