Get List of Available Data Frames

Get list of available data frames

You can use eapply to loop through the objects in an environment:

x <- 1:10
y <- mtcars
eapply(.GlobalEnv,is.data.frame)
$x
[1] FALSE

$y
[1] TRUE

names(which(unlist(eapply(.GlobalEnv,is.data.frame))))
[1] "y"

Pandas Get a List Of All Data Frames loaded into memory

You could list all dataframes with the following:

import pandas as pd

# create dummy dataframes
df1 = pd.DataFrame({'Col1' : list(range(100))})
df2 = pd.DataFrame({'Col1' : list(range(100))})

# check whether all variables in scope are pandas dataframe.
# Dir() will return a list of string representations of the variables.
# Simply evaluate and test whether they are pandas dataframes
alldfs = [var for var in dir() if isinstance(eval(var), pd.core.frame.DataFrame)]

print(alldfs) # df1, df2

How do I make a list of data frames?

This isn't related to your question, but you want to use = and not <- within the function call. If you use <-, you'll end up creating variables y1 and y2 in whatever environment you're working in:

d1 <- data.frame(y1 <- c(1, 2, 3), y2 <- c(4, 5, 6))
y1
# [1] 1 2 3
y2
# [1] 4 5 6

This won't have the seemingly desired effect of creating column names in the data frame:

d1
# y1....c.1..2..3. y2....c.4..5..6.
# 1 1 4
# 2 2 5
# 3 3 6

The = operator, on the other hand, will associate your vectors with arguments to data.frame.

As for your question, making a list of data frames is easy:

d1 <- data.frame(y1 = c(1, 2, 3), y2 = c(4, 5, 6))
d2 <- data.frame(y1 = c(3, 2, 1), y2 = c(6, 5, 4))
my.list <- list(d1, d2)

You access the data frames just like you would access any other list element:

my.list[[1]]
# y1 y2
# 1 1 4
# 2 2 5
# 3 3 6

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

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))

How can I get a list of data frames based on pattern in the middle of the data frame name?

You could try

list_df <- mget(ls(pattern = "^df\\d+b$"))

This would get all the objects which start with df have a number in between and ends with b.

How to make a functional list with the data.frames from the environment in R?

If we have multiple data.frames in the global environment that we want to merge, we can use mget and ls:

file_1 = data.frame(id = c(1,2), a = c(1,2))
file_2 = data.frame(id = c(1,2), b = c(3,4))
file_3 = data.frame(id = c(3,4), a = c(5,6))

Reduce(\(...) merge(..., all = T), mget(ls(pattern = "file")))
id a b
1 1 1 3
2 2 2 4
3 3 5 NA
4 4 6 NA


Related Topics



Leave a reply



Submit