【问题标题】:Tidy Evaluation not working with mutate and stringr整洁的评估不适用于 mutate 和 stringr
【发布时间】:2020-04-23 01:08:06
【问题描述】:

我尝试在 mutate 管道内同时使用 Tidy Eval 和 Stringr,但每次运行它都会给我带来不希望的结果。 它没有将字母“a”更改为字母“X”,而是用列名覆盖整个向量,正如您在下面的示例中所见,它使用了 IRIS 数据集。

text_col="Species"
iris %>% 
  mutate({{text_col}} := str_replace_all({{text_col}}, pattern = "a", replacement = "X"))

结果:

    structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4, 4.6, 
5, 4.4, 4.9, 5.4, 4.8, 4.8, 4.3, 5.8), Sepal.Width = c(3.5, 3, 
3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.4, 3, 3, 4), Petal.Length = c(1.4, 
1.4, 1.3, 1.5, 1.4, 1.7, 1.4, 1.5, 1.4, 1.5, 1.5, 1.6, 1.4, 1.1, 
1.2), Petal.Width = c(0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 
0.2, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2), Species = c("Species", "Species", 
"Species", "Species", "Species", "Species", "Species", "Species", 
"Species", "Species", "Species", "Species", "Species", "Species", 
"Species")), row.names = c(NA, 15L), class = "data.frame")

Stringr 不支持 tidy 评估或 curly-curly ({{}}) 运算符吗??

【问题讨论】:

    标签: r dplyr stringr tidyeval


    【解决方案1】:

    整洁的评估完全取决于您发送输入的方式。

    例如,如果您将输入作为不带引号的变量发送,您的尝试将起作用。

    library(dplyr)
    library(stringr)
    library(rlang)
    
    change_fun <- function(df, text_col) {
      df %>%  mutate({{text_col}} := str_replace_all({{text_col}}, "a","X"))
    }
    
    change_fun(iris, Species) %>% head
    
    #  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
    #1          5.1         3.5          1.4         0.2  setosX
    #2          4.9         3.0          1.4         0.2  setosX
    #3          4.7         3.2          1.3         0.2  setosX
    #4          4.6         3.1          1.5         0.2  setosX
    #5          5.0         3.6          1.4         0.2  setosX
    #6          5.4         3.9          1.7         0.4  setosX
    

    要将输入作为引用变量传递,请先使用sym 转换为符号,然后评估!!

    change_fun <- function(df, text_col) {
       df %>%  mutate(!!text_col := str_replace_all(!!sym(text_col), "a","X"))
    }
    
    change_fun(iris, "Species") %>% head
    
    #  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
    #1          5.1         3.5          1.4         0.2  setosX
    #2          4.9         3.0          1.4         0.2  setosX
    #3          4.7         3.2          1.3         0.2  setosX
    #4          4.6         3.1          1.5         0.2  setosX
    #5          5.0         3.6          1.4         0.2  setosX
    #6          5.4         3.9          1.7         0.4  setosX
    

    【讨论】:

      猜你喜欢
      • 2018-06-10
      • 1970-01-01
      • 2017-11-16
      • 2020-04-28
      • 2020-11-29
      • 2021-12-01
      • 2021-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多