0

How to save an object generated by "assign" function as .RData file in a loop? Here is an example.

for (ii in 1:3){
QQ=matrix(runif(15),5,3)
assign(paste0("FF", ii),QQ) 
}
1
  • library("fortunes"); fortune(236) stackoverflow.com/questions/17559390/… Learn to use lists: QQlist <- lapply(1:3, function(ii) matrix(runif(15),5,3)) or QQlist <- replicate(3, matrix(runif(15),5,3), simplify = FALSE) Commented Aug 7, 2018 at 6:58

1 Answer 1

2

Personally, I find that .RDS files are better suited to save single objects. For instance:

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

Given the results:

# [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"

To access second of the saved objects:

>> 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.