lucacerone
lucacerone

Reputation: 10119

How to import R datasets with the same name

I have three dataset saved in R format A.RData, B.RData, C.RData (each of the size of ~2Gb). Each of the files contains three variables X, Y, Z.

I can not load A.RData and B.RData without first renaming the variables. As the datasets are big these steps:

load("A.RData")
A = list(X=X,Y=Y,Z=Z)
rm(X,Y,Z)

load("B.RData")
B = list(X=X,Y=Y,Z=Z)
rm(X,Y,Z)

take some time.

Is there a way to import the data from A.RData directly in a list A, without having to make copies of the variable?

Upvotes: 2

Views: 320

Answers (2)

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

The solution provided by Matthew Plourde is the way to go. In future, you can avoid these problems if you save your data with saveRDS (not save).

The function saveRDS saves a single object. For example:

X <- 1
Y <- 2
Z <- 3

# put the objects in a list
mylist <- list(X, Y, Z)

# save the list
saveRDS(mylist, file = "myfile.rds")
rm(X, Y, Z, mylist) # remove objects (not necessary)

# load the list
newlist <- readRDS("myfile.rds")
# [[1]]
# [1] 1
# 
# [[2]]
# [1] 2
# 
# [[3]]
# [1] 3

In contrast to save, the name of the object is not stored. Hence, you can assign the result of readRDS to another name. Note that you have to put all variables in one list.

Upvotes: 0

Matthew Plourde
Matthew Plourde

Reputation: 44614

Yes, there is.

A <- new.env()
load('A.RData', envir=A)
A <- as.list(A)

Upvotes: 1

Related Questions