How can I access all objects of class data.frame inside .GlobalEnv in R

I have 8,000 data.frames inside my global environment (.GlobalEnv) in R, for example

head(ls(.GlobalEnv))
#[1] "db1" "db2" "db3" "db4" "db5"
tail(ls(.GlobalEnv))
#[1] "db7996" "db7997" "db7998" "db7999" "db8000"

How can I access each of the data.frames?

I could access the data.frames using .GlobalEnv$"db1", but it is useless because I want to carry out a linear regression for each one.

Answer #1:

You could use a combination of eapply and mget to put all data.frames that are present in the global environment in a list:

x <- eapply(.GlobalEnv, 'is.data.frame')
dflist <- mget(names(x[unlist(x)]), .GlobalEnv)

Then you can use for example lapply(dflist, ...) to run a regression on each of them.


A very concise alternative approach contributed by @RichardScriven in the comments is:

dflist <- Filter(is.data.frame, as.list(.GlobalEnv))
Answered By: talat

Answer #2:

The simplest approach I can think of would be a basic for loop using mget.

for(df in ls(.GlobalEnv)){
    print(get(df))
}

You can then apply whatever operation you like on the mget result.

Note - this assumes the only variables in the environment are data.frames for your purposes as it doesn't discriminate A more restrictive for loop would be:

for(df in ls(.GlobalEnv)){
    if(is.data.frame(get(df))){
        print(head(get(df)))
    }
}

which just uses is.data.frame to check if the object is indeed a data.frame.

Answered By: cdeterman

Answer #3:

Perhaps:

.Globalenv[ls()]

Can also restrict to only items beginning with 'db' using regex patterns

Answered By: IRTFM

Answer #4:

I have found another solution:

db1 <- data.frame(x = c(1,2,3),y = c(1.1,1.2,1.3))
db2 <- data.frame(x = c(1,2,3,4),y = c(2,2.1,2.2,2.3))
db3 <- data.frame(x = c(1,2,3,4,5),y = c(3,3.1,3.2,3.3,3.4))
ls()
#[1] "db1" "db2" "db3"
nombres <- ls()
eval(parse(text = nombres[1]))
#  x   y
#1 1 1.1
#2 2 1.2
#3 3 1.3
lm(y~x,data = eval(parse(text = nombres[1])))

Thanks!

Answered By: Francisco Ariel
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles