整洁的评估不适用于mutate和stringer [英] Tidy Evaluation not working with mutate and stringr
问题描述
我试图在变异管道中使用Tidy Eval和Stringr togheter,但是每次运行它都会给我带来不良结果.如下面的示例所示,使用IRIS数据集,而不是将字母"X"更改为字母"a",而是使用列名覆盖了整个向量.
I've trying to use Tidy Eval and Stringr togheter inside a mutate pipe, but every time I run it it gives me an undesirable result. Instead of changing the letter 'a' for the letter 'X', it overwrite the entire vector with the column name, as you can see in the example below, that uses the IRIS dataset.
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不支持整洁的评估或卷曲的( {{}}
)运算符吗?
Doesn't Stringr supports tidy evaluation or the curly-curly ({{}}
) operator??
推荐答案
整洁的评估完全取决于您发送输入的方式.
Tidy evaluation completely depends on how you send your inputs.
例如,如果您将输入作为未加引号的变量发送,则您的尝试将起作用.
For example, if you send your input as an unquoted variable your attempt would work.
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
首先转换为符号,然后求值 !!
.
To pass input as quoted variables use sym
to convert into symbol first and then evaluate !!
.
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
这篇关于整洁的评估不适用于mutate和stringer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!