How can I list all the data frames that are in my global environment?

I am trying to use rbind for them. But I need a list of all dataframes that are already in my global environment. How can i do this?

The code I used to import 20 csv files in a directory. In principle, you need to combine in a single data block.

 temp = list.files(pattern = "*.csv") for (i in 1:length(temp)) assign(temp[i], read.csv(temp[i])) 
+9
source share
6 answers

From your published code, I would recommend that you start a new R session and read the files with the following code again

 do.call(rbind, lapply(list.files(pattern = ".csv"), read.csv)) 
+8
source

This function should return a valid list with all data.frames as elements

 dfs <- Filter(function(x) is(x, "data.frame"), mget(ls())) 

then you can redo them with

 do.call(rbind, dfs) 

Of course, it is terribly stupid to have a bunch of data.frames lying around that are so connected that you want to rbind them. Looks like they probably should have been on the list first.

I recommend that you tell assign() that the sign is always a violation. Try

 temp <- list.files(pattern="*.csv") dfs <- lapply(temp, read.csv) 

which should return the list immediately.

+19
source

This is a small improvement in MentatOfDune's answer that does not capture data.frames with multiple classes:

 ls()[grepl('data.frame', sapply(ls(), function(x) class(get(x))))] 
+5
source

The ls function lists everything in your environment. The get function gets the variable with the given name. You can use the class function to get the class of a variable.

If you put them all together, you can do this:

 ls()[sapply(ls(), function(x) class(get(x))) == 'data.frame'] 

which will return the character vector to data.frames frames in the current environment.

+4
source

If you only have data with the same number of columns and column names in your global environment, the following should work (the non-data.frame object does not matter):

 do.call(rbind, eapply(.GlobalEnv,function(x) if(is.data.frame(x)) x)) 
+4
source

To improve MentatOfDune's answer (by the way, a great username):

 ls()[sapply(ls(), function(x) any(class(get(x)) == 'data.frame'))] 

or even more reliable:

 ls()[sapply(ls(), function(x) any(is.data.frame(get(x))))] 

It also supports tibbles (e.g. created using dplyr ), as they contain several classes where data.frame is one of them.

+1
source

Source: https://habr.com/ru/post/1201166/


All Articles