4

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.

M--
  • 25,431
  • 8
  • 61
  • 93
PJC
  • 61
  • 2
  • you can also use `data.table` library and use the function `tables()` from it - this function also shows tables' sizes (nrow, ncol, amount of RAM) – inscaven Sep 03 '20 at 12:56
  • While this is specifically asking about making this into a function, that part is as easy as doing ```function.name <- function() { Whatever solution you have }```. That is one of the basics of R programming, which falls into lack of research. All the answers here, except the part that I mentioned above can be found in the dupe target I closed this question with. Please consider this before reopening. Other option would've been closing with a comment indicating lack of research. p.s. PJC this is not directed at you, just a comment to clarify my thoughts. Cheers and Welcome to SO :) – M-- Sep 03 '20 at 16:05
  • Thanks M--. I have much to learn! – PJC Sep 04 '20 at 14:17

3 Answers3

4

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()
Bas
  • 4,628
  • 1
  • 14
  • 16
2

Maybe you can try the code below

list.df <- function() names(Filter(is.data.frame,mget(ls())))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
2

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.