Inside some functions as dplyr::mutate_at
or purrr::map
, it seems that one can use tilde operator ~
to build anonymous functions.
For example, one can do as in the linked question: map(iris, ~length(unique(.)))
Or also: mtcars %>% mutate_all(~.*2)
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
A reproducible example:
> 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
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?
Thank you!