Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error when trying to reference a variable/column inside a function

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.")
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading