0

I'm new to R and was trying to write a function to search for an object in all the environments.

The following piece of lines work fine but when I include them inside a 'while' loop, they don't work. I think I'm missing something here. Any help?

    name<-10
    env=parent.frame()
    !identical(env,emptyenv())
    exists('name',envir=env,inherits = FALSE)
    env<-parent.env(env)
    env

Codes in while loop

    MyWhere<-function(name,env=parent.frame){
       while(!identical(env,emptyenv())){
    if (exists(name,envir=env,inherits = FALSE)) {
        env
       }
    else {
        env<-parent.env(env)
        }
      }
    }

    MyWhere('a')

Error message - Error in exists(name, envir = env, inherits = FALSE) : invalid 'envir' argument

1
  • Note that in R, usage of spaces around the <- operator is usually encouraged. Commented Sep 1, 2015 at 20:37

2 Answers 2

1

There's a typo: you need to add parentheses in the call to parent.frame()

MyWhere<-function(name,env=parent.frame()){

Without the parentheses you're passing in a 'function' instead of an 'environment' object, resulting in the error.

Sign up to request clarification or add additional context in comments.

Comments

1

You have a few problems here. The error you're getting is because you're passing parent.env, a function, instead of parent.env(), an environment, as the default environment value.

Further, you don't return the environment when you match the name, which leads to an infinite loop when your function matches. Lastly, the function doesn't return the empty environment when it doesn't match.

When you fix these, it seems to work:

MyWhere<-function(name,env=parent.frame()){
  while(!identical(env,emptyenv())){
    if (exists(name,envir=env,inherits = FALSE)) {
      return(env)
    } else {
      env<-parent.env(env)
    }
  }
  return(env)
}

foo <- 3
MyWhere('foo')
# <environment: R_GlobalEnv>
MyWhere('blah')
# <environment: R_EmptyEnv>
library(ggplot2)
MyWhere('geom_line')
# <environment: package:ggplot2>
# attr(,"name")
# [1] "package:ggplot2"
# attr(,"path")
# [1] "/Library/Frameworks/R.framework/Versions/3.2/Resources/library/ggplot2"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.