r-lib / rlang

Low-level API for programming with R
https://rlang.r-lib.org
Other
500 stars 137 forks source link

Embrase does not work #1539

Closed alexander-pastukhov closed 1 year ago

alexander-pastukhov commented 1 year ago

I am confused, because I don't know whether it is me or specific setup but embrace {{}} does not work for me.

Taking the example from documentation

my_mean <- function(data, var) { dplyr::summarise(data, mean = mean({{ var }})) }

and using it as data <- ggplot2::mpg var <- "cyl" dplyr::summarise(data, mean = mean({{ var }}))

produces an NA as mean and the following warning message:

In mean.default(~"cyl") : argument is not numeric or logical: returning NA

Same if I use "Under the hood" code snippet: dplyr::summarise(data, mean = mean(!!enquo(var)))

But it does work via dplyr::summarise(data, mean = mean(!!sym(var)))

Tested on three installations (all windows) with only dplyr and rlang libraries loaded:

I suspect there is some trivial explanation but I am completely at loss and any help is highly appreciated!

hadley commented 1 year ago

I'd recommend reading https://r4ds.hadley.nz/functions.html#data-frame-functions.

alexander-pastukhov commented 1 year ago

@hadley, thank you for the tip (and for all the fantastic work you do for the R community)! With regard to the issue: Perhaps small edits of documentation for embrace are in order, with the actual example of calling the function: once I saw how the variable name is passed, I immediately realized why it was not working for me but it is not obvious from the docs because the function is never called? And, perhaps, a brief reminder that you need different tools if you want to get the same functionality but with variable name as a string with a pointer towards the documentation topic? For a typical R user, passing variable name to their own function without quotes is probably very unintuitive and the fact that the whole thing does not work without being wrapped into a function is totally not obvious (documentation hints at that but does not explicitly say that and you need to read the vignette to learn about this). Sorry if I sound negative and picky, but this is a brilliant functionality, which I feel is underused because of these small important details, which are a bit hard to figure out from the brief embrace documentation.