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

R get local variable from formula

Consider the R code :

foo <- function(formula){
    Y <- get(formula[[2]])
    print(Y)
}
main <- function(){
    Y <- 1
    X <- 2
    foo(Y ~ X)
}
main()

The outcome says that in get(formula[[2]]), it cannot find object Y.
How can I make a function read formula in a local setting?
How do I change the code so that it runs and prints Y?

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

>Solution :

By default get will look for Y in the the current environment of the call to get, which is just what is available in foo itself (i.e. pos = -1). One of the nice things about R formulas is that they have an associated environment as an attribute, so we can specify to get that it should look in that environment instead:

foo <- function(formula){
  Y <- get(formula[[2]], environment(formula))
  print(Y)
}

main()
[1] 1

Specifying the environment is a good idea generally, so that e.g. this will still get the Y from the original context:

foo <- function(formula){
  Y <- 3
  bar <- get(formula[[2]], environment(formula))
  print(bar)
}
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