问题描述
在诸如 dplyr::mutate_at
或 purrr::map
的一些函数中,它似乎可以使用波浪号运算符~
来构建匿名函数.
Inside some functions as dplyr::mutate_at
or purrr::map
, it seems that one can use tilde operator ~
to build anonymous functions.
例如,您可以按照链接的问题进行操作:map(iris, ~length(unique(.)))
For example, one can do as in the linked question: map(iris, ~length(unique(.)))
或者:mtcars %>% mutate_all(~.*2)
我试图在 sapply
中模仿这个,以避免 sapply(list, function(item) {something_with_item})
.我正在编写 sapply(list, ~ something_with_.)
但我收到一个错误
I tried to imitate this inside sapply
, to avoid sapply(list, function(item) {something_with_item})
. I was writing sapply(list, ~ something_with_.)
but I get an error
Error in match.fun(FUN) :
'~ something_with_.' is not a function, character or symbol
一个可重现的例子:
> sapply(names(mtcars),function(item) mean(mtcars[[item]]))
mpg cyl disp hp drat wt qsec
20.090625 6.187500 230.721875 146.687500 3.596563 3.217250 17.848750
vs am gear carb
0.437500 0.406250 3.687500 2.812500
> sapply(names(mtcars),~mean(mtcars[[.]]))
Error in match.fun(FUN) :
'~mean(mtcars[[.]])' is not a function, character or symbol
为什么?将此语法理解为函数只是某些包的行为,例如dplyr
和purrr
?对于某些特殊情况,它是否可以被基本的 R
理解?
Why? Understanding this syntaxis as a function is just a behaviour of some packages as dplyr
and purrr
? Is it understood by base R
for some special cases?
谢谢!
推荐答案
正如上面 caldwellst 所说的,tilda ~
用于创建一个公式对象,这是一个有点未评估的代码,可以以后用.公式与函数不同,purrr
函数与公式一起工作,因为它们调用 rlang::as_function
(通过 purrr::as_mapper
代码>)在后台.*apply
函数显然不会这样做,尽管您可以通过在自己修改的 *apply
函数中调用上述函数之一来模仿这种行为(最好只是使用map
函数,以下只是为了说明问题):
As caldwellst says above, the tilda ~
is used to create a formula object, which is a bit of unevaluated code that can be used later. Formulae are not the same as functions, and the purrr
functions work with formulae because they make a call to rlang::as_function
(via purrr::as_mapper
) in the background. The *apply
functions obviously don't do this, though you can imitate this behavior by calling one of the above functions in your own modified *apply
function (it's better to just use the map
functions, the following is just to illustrate the point):
# Write function with `as_mapper()`.
fapply <- function(x, func) {
sapply(x, purrr::as_mapper(func))
}
# Now we can use formulae.
fapply(names(mtcars), ~ mean(mtcars[[.]]))
#### OUTPUT ####
mpg cyl disp hp drat wt qsec vs am gear carb
20.090625 6.187500 230.721875 146.687500 3.596563 3.217250 17.848750 0.437500 0.406250 3.687500 2.812500
这篇关于波浪号运算符可以用于构建匿名函数的通用性是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!