Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a list of all dataframes that are in my global environment?

Tags:

r

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

Code I used to import the 20 csv files in a directory. Basically, have to combine into a single dataframe.

temp = list.files(pattern = "*.csv")
for (i in 1:length(temp)) assign(temp[i], read.csv(temp[i]))
like image 430
maximusyoda Avatar asked Aug 26 '14 15:08

maximusyoda


People also ask

Can I create a list of Dataframes?

To create a list of Dataframes we use the list() function in R and then pass each of the data frame you have created as arguments to the function.

How do I create a global environment in R?

Global environment can be referred to as . GlobalEnv in R codes as well. We can use the ls() function to show what variables and functions are defined in the current environment. Moreover, we can use the environment() function to get the current environment.

What are Dataframes in R?

Data Frames are data displayed in a format as a table. Data Frames can have different types of data inside it. While the first column can be character , the second and third can be numeric or logical . However, each column should have the same type of data.


2 Answers

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

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

then you can rbind them with

do.call(rbind, dfs)

Of course it's awfully silly to have a bunch of data.frames lying around that are so related that you want to rbind them. It sounds like they probably should have been in a list in the first place.

I recommend you say away from assign(), that's always a sign things are probably afoul. Try

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

that should return a list straight away.

like image 117
MrFlick Avatar answered Sep 30 '22 07:09

MrFlick


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

do.call(rbind, lapply(list.files(pattern = ".csv"), read.csv))
like image 27
Rich Scriven Avatar answered Sep 30 '22 06:09

Rich Scriven