r - 如何在带有公式而不是 .dots 和 mutate_ 的函数中使用 mutate?

标签 r dplyr mutate nse

我曾经使用 mutate_ 和 .dots 参数来评估函数内部的一组公式,使用用户提供的变量(字符串格式)和函数内部计算的变量(如下面的 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 相同的结果?
如果我可以继续使用这些公式会容易得多。

最佳答案

我的建议是从公式切换到表达式,然后使用取消引用拼接运算符 !!!与常规 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

关于r - 如何在带有公式而不是 .dots 和 mutate_ 的函数中使用 mutate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63753232/

相关文章:

R: gsub 删除\

用 R 中该行的最新非 NA 值替换特定列中的 NA

r - dplyr:为什么不使用 summarise() 来汇总案例?

r - 使用 dplyr 更改列类型

满足条件的特定列的行和

r - 导出多个匹配模式

regex - 是否有更有效的方法使用 dplyr 过滤器从数据框中删除行?

r - 如何按组填写范围内缺失的日期

r - 如何有效地检查R中的特定值并标记包含该值的行中的变量?

r - R函数来标识与先前元素相同的元素