In R, I am trying find the maximum value of a variable in a dataset inside a function but I can’t figure out the correct way to reference the variable.
df <- data.frame(a = 1:3, b = 2:4)
I’ve written the function as
f <- function(var) {
m <- max(df${{var}})
if (m == 3) {
print("It's 3.")
}
}
with the intention to call it like so: f(a)
However, when trying the define the function I get the following error:
Error: unexpected '{' in:
"f <- function(var) {
m <- max(df${"
I appreciate any help with this.
>Solution :
Apparently you are trying to use tidy evaluation syntax, in particular “curly-curly”.
Tidy evaluation only works with specific functions which explicitly support it. To find out whether a function supports tidy evaluation, consult its documentation. But, in particular, no base-R function or operator supports it, including $.
And while you could redefine $, the syntax rules of the R language prohibit $ from supporting tidy evaluation even then, because the right-hand operator of $ must always be a bare name or a quoted string — nothing else is allowed.
Put differently, you cannot use $ with variables or parameters. Instead, you can use [[…]] subsetting. However, that also does not work with the curly-curly syntax. You need to deparse the argument name manually:
f <- function(var) {
var_name <- as.character(substitute(var))
m <- max(df[[var_name]])
if (m == 3) {
print("It's 3.")
}
}