Context
I want to use non-standard evaluation with dollar sign in R.
I want to customize a function with two parameters. data
is the input data frame, var
is the name of the variable in the input data frame. The return value is the value corresponding to the variable name.
I can do this with fun1
.
library(dplyr)
df = data.frame(a = 1:3)
fun1 <- function(data, var){
data %>% pull({{var}})
}
> fun1(data = df, var = a)
[1] 1 2 3
Question
Is there any way to perform the function of fun1
with non-standard evaluation and dollar signs($
).
My solution is as follows (fun2
) but it reports an error.
fun2 <- function(data, var){ # Can't create fun2, it will report an error.
data${{var}}
}
fun2(data = df, var = a)
We may use [[
to extract after converting the unquoted to string
fun2 <- function(data, var){
var <- deparse(substitute(var))
data[[var]]
}
-testing
> fun2(data = df, var = a)
[1] 1 2 3
It is better to use [[
instead of $
. In case, we want to only use $
, then paste
the names and eval
(not recommended)
fun2 <- function(data, var) {
argslist <- as.list(match.call()[-1])
eval(parse(text = sprintf('%s$%s',
deparse(argslist$data), deparse(argslist$var))))
}
> fun2(df, a)
[1] 1 2 3