如何将“分配”功能生成的对象保存为循环中的.Rdata文件

时间:2018-08-07 06:53:10

标签: r loops save assign

如何在循环中将“分配”功能生成的对象另存为.RData文件?这是一个例子。

for (ii in 1:3){
QQ=matrix(runif(15),5,3)
assign(paste0("FF", ii),QQ) 
}

1 个答案:

答案 0 :(得分:2)

我个人认为.RDS文件更适合保存单个对象。例如:

for (ii in 1:3) {
    QQ = matrix(runif(15), 5, 3)
    object_name <- paste0("FF", ii)
    assign(object_name, QQ)
    tmp_fle <- tempfile(pattern = object_name, fileext = ".RDS")
    print(tmp_fle)
    saveRDS(
        object = get(x = object_name),
        file = tmp_fle
    )
}

给出结果:

# [1] "/var/folders/7x/kwc1y_l96t55_rwlv35mg8xh0000gn/T//Rtmpsj0j8h/FF1afe6b0a300.RDS"
# [1] "/var/folders/7x/kwc1y_l96t55_rwlv35mg8xh0000gn/T//Rtmpsj0j8h/FF2afe369d586e.RDS"
# [1] "/var/folders/7x/kwc1y_l96t55_rwlv35mg8xh0000gn/T//Rtmpsj0j8h/FF3afe1418b9c5.RDS"

要访问第二个已保存的对象,请执行以下操作:

>> readRDS("/var/folders/7x/kwc1y_l96t55_rwlv35mg8xh0000gn/T//Rtmpsj0j8h/FF2afe369d586e.RDS")
           [,1]      [,2]      [,3]
[1,] 0.38537636 0.2969078 0.9603315
[2,] 0.08339023 0.9127538 0.6552166
[3,] 0.55220069 0.4384881 0.5345182
[4,] 0.10179912 0.6353755 0.8247961
[5,] 0.63983736 0.8858784 0.8904668