How to search an environment using ls() inside a function?

You need to tell your function to list objects in an environment other than itself, e.g. the global environment. (And while you're at it, you can also specify the regex pattern as an argument to ls.):

find.test <- function(x, envir=.GlobalEnv) {
  ls(pattern=x, envir=envir) 
}

See ?ls for more info about ls() and ?environment for other options to specify the environment.


  1. Why not use the pattern= argument to ls?
  2. Calling ls inside a function lists the objects that exist within the function scope, not the global environment (this is explained in ?ls).

If you want to list the objects in the global environment from a function, specify envir=.GlobalEnv.

x <- 1:10
f <- function() ls()
g <- function() ls(envir=.GlobalEnv)
h <- function() ls(envir=.GlobalEnv, pattern="[fg]")
f()
# character(0)
g()
# [1] "f" "g" "h" "x"
h()
# [1] "f" "g"

Tags:

Environment

R