Llist dataframe names in Global environment

Viewed 144

I am trying to write a function that lists the names of dataframes in my global environment.

I can do this by using the code:

l<-ls()
l[sapply(l, function(x) is.data.frame(get(x)))]

I need to convert this into a function that I can easily call upon.

3 Answers

You have to be aware that ls() by default lists objects in the current environment. If you wrap your code in a function, this current environment is the internal function environment, which is empty at that point (we are at the first line of the function and nothing has been defined yet). Since you are interested in the global environment, you have to explicitly specify this with .GlobalEnv:

lsf <- function() {
  l<-ls(.GlobalEnv)
  l[sapply(l, function(x) is.data.frame(get(x, envir = .GlobalEnv)))]
}

lsf()

Maybe you can try the code below

list.df <- function() names(Filter(is.data.frame,mget(ls())))

You can use as.list on an environment and then use sapply with is.whatever like this:

list_all_x <- function(is.x = is.data.frame, env = .GlobalEnv){
  env <- as.list(env)
  names(env)[sapply(env, is.x)]
}

# or related to ThomasIsCoding's great answer
list_all_x <- function(is.x = is.data.frame, env = .GlobalEnv)
   names(Filter(is.x, as.list(env)))

# check the function
d1 <- numeric()
d2 <- data.frame()
d3 <- data.frame()
  
list_all_x()
#R> [1] "d2" "d3"
list_all_x(is.x = is.numeric)
#R> [1] "d1"

You can use the above if you want to apply the function to another environment using the env argument or look for another type by changing the is.x argument as shown above.

Related