简体   繁体   English

如何导入具有相同名称的R数据集

[英]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). 我有三个以R格式保存的数据集A.RData,B.RData,C.RData(每个大小约为2Gb)。 Each of the files contains three variables X, Y, Z. 每个文件包含三个变量X,Y,Z。

I can not load A.RData and B.RData without first renaming the variables. 我必须先重命名变量才能加载A.RData和B.RData。 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? 有没有一种方法可以直接从列表中的A.RData导入数据,而不必复制变量?

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. Matthew Plourde提供的解决方案是必经之路。 In future, you can avoid these problems if you save your data with saveRDS (not save ). 将来,如果使用saveRDS (而不是save )保存数据,则可以避免这些问题。

The function saveRDS saves a single object. 函数saveRDS保存单个对象。 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. save相反, 存储对象的名称。 Hence, you can assign the result of readRDS to another name. 因此,您可以将readRDS的结果分配给另一个名称。 Note that you have to put all variables in one list. 请注意,您必须将所有变量放在一个列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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