简体   繁体   中英

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?

Yes, there is.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM