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
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))
To improve MentatOfDune's answer (great username by the way):
ls()[sapply(ls(), function(x) any(class(get(x)) == 'data.frame'))]
or even more robust:
ls()[sapply(ls(), function(x) any(is.data.frame(get(x))))]
This also supports tibbles (created with dplyr
for example), because they contain multiple classes, where data.frame
is one of them.
The ls
function lists all things in your environment. The get
function gets a variable with a 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 a character vector of the data.frames in the current environment.
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.
This is a slight improvement on MentatOfDune's answer, which does not catch data.frames with multiple classes:
ls()[grepl('data.frame', sapply(ls(), function(x) class(get(x))))]
If you only have data.frames with the same number of columns and column names in you global environment, the following should work (non-data.frame object don't matter):
do.call(rbind, eapply(.GlobalEnv,function(x) if(is.data.frame(x)) x))