Reputation: 615
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]))
Upvotes: 24
Views: 34662
Reputation: 206187
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 stay 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.
Upvotes: 34
Reputation: 5189
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) 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.
A readable version to get TRUE
s and FALSE
s using R 4 and higher:
ls() |> sapply(get) |> sapply(is.data.frame)
Finally super, super robust, also for package developers:
ls()[sapply(ls(), function(x) is.data.frame(eval(parse(text = x), envir = globalenv())))]
Upvotes: 5
Reputation: 1843
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))))]
Upvotes: 6
Reputation: 99331
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))
Upvotes: 12
Reputation: 66834
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))
Upvotes: 7
Reputation: 309
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.
Upvotes: 7