[英]What does the !! operator mean in R, particularly in the context !!sym("x")
What does "!!" “!!”是什么意思do in R, and why would you use it?
在 R 中做,为什么要使用它?
Specifically, I'm looking at a function that involves the phrase a = !!sym("x")
where "x"
is a string.具体来说,我正在查看一个包含短语
a = !!sym("x")
的函数,其中"x"
是一个字符串。 I thought sym
worked by turning a string into an object, so a = sym("x")
would set a
equal to the object x
.我认为
sym
通过将字符串转换为对象来工作,因此a = sym("x")
会将a
设置a
等于对象x
。 What is the !!
什么是
!!
there for?那里? I read that it unquotes whatever is after it, but I thought
sym
itself unquoted strings?我读到它没有引用它后面的任何内容,但我认为
sym
本身没有引用字符串?
I also see !!
我也看到了
!!
used with other functions.与其他功能一起使用。 What is it doing?
它在做什么?
When you convert a string to a symbol, it prints without the quotes, but that's NOT what unquoting means (we'll get back to that in the end).当您将字符串转换为符号时,它会在不带引号的情况下打印,但这不是不加引号的意思(我们最后会回到那个问题)。
rlang::sym()
is creating a symbol from a string, it's almost the same as base::as.symbol()
(tiny differences irrelevant to this answer), itself an alias for base::as.name()
: rlang::sym()
正在从字符串创建一个符号,它几乎与base::as.symbol()
(与此答案无关的微小差异),它本身是base::as.name()
的别名:
nm <- "Sepal.Width"
x <- rlang::sym(nm)
x
#> Sepal.Width
typeof(x)
#> [1] "symbol"
identical(x, as.symbol(nm))
#> [1] TRUE
Those don't work, as x
and nm
are respectively a symbol and a character, so I can't multiply them by 2
:那些不起作用,因为
x
和nm
分别是一个符号和一个字符,所以我不能将它们乘以2
:
dplyr::mutate(head(iris),SW2 = nm * 2)
#> Error in nm * 2: argument non numérique pour un opérateur binaire
dplyr::mutate(head(iris),SW2 = x * 2)
#> Error in x * 2: argument non numérique pour un opérateur binaire
!!
doesn't do anything by itself and is not a real operator, it tells mutate()
to do something though, because mutate()
is designed to recognize it.本身不做任何事情,也不是真正的运算符,它告诉
mutate()
做某事,因为mutate()
旨在识别它。
What it tells to mutate()
is to act as if !!x
was replaced by the quoted content of x.它告诉
mutate()
就像!!x
被!!x
的引用内容替换一样。
# equivalent to dplyr::mutate(head(iris), Sepal.Width * 2)
dplyr::mutate(head(iris), !!x * 2)
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1 5.1 3.5 1.4 0.2 setosa
#> 2 4.9 3.0 1.4 0.2 setosa
#> 3 4.7 3.2 1.3 0.2 setosa
#> 4 4.6 3.1 1.5 0.2 setosa
#> 5 5.0 3.6 1.4 0.2 setosa
#> 6 5.4 3.9 1.7 0.4 setosa
#> Sepal.Width * 2
#> 1 7.0
#> 2 6.0
#> 3 6.4
#> 4 6.2
#> 5 7.2
#> 6 7.8
dplyr::mutate(head(iris), !!sym("Sepal.Width") * 2)
would give the same output. dplyr::mutate(head(iris), !!sym("Sepal.Width") * 2)
会给出相同的输出。
Why it is called unquoting might be easier to understand by looking at this other equivalent call :通过查看另一个等效调用可能更容易理解为什么它被称为取消引用:
quoted <- quote(Sepal.Width * 2)
dplyr::mutate(head(iris), !!quoted)
See help("!!")
for more details.有关更多详细信息,请参阅
help("!!")
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.