Search code examples
rdataframeloopssave

Iteratively save .Rds data.frame objects with R


I need to save iteratively data.frame objects on drive.

A similar issue was already posted here but ultimately, and to my point of view, missed the answer because:

  1. The author of the question correctly asked to save the data.frame as .Rds file, but ended up writing code about .Rda;
  2. The author of the accepted answer uses save() whereas saveRDS() should have been used. Failing to do so, command readRDS won't read corresponding files.

My question:

  • What piece of code do I need in order to iteratively save .Rds files?

Solution

  • Here below is a piece of, hopefully reproducible, piece of code (with comments) that worked very well for me (links in comments are where code has been found to adapt to situation):

    # 1. Load some data from the Internet and close connections
    library(quantmod)
    tickers <- c("SHOP", "MPNGF", "BABA", "JD")
    getSymbols.yahoo(tickers, auto.assign = TRUE, env = globalenv())
    closeAllConnections()
    
    
    # 2. Find all loaded xts files
    xtsObjects <- names(which(unlist(eapply(.GlobalEnv, is.xts))))
    
    
    # 3. Iteratively convert found xts files under 2. into data.frames
    # https://stackoverflow.com/a/69246047/2950721
    library(zoo)
    for (i in seq_along(xtsObjects)) {
      assign(xtsObjects[i], fortify.zoo(get(xtsObjects[i])))
    }
    
    # 4. Iteratively save converted data.frame objects as .Rds files
    # https://stackoverflow.com/a/8345810/2950721
    # https://stackoverflow.com/a/69246047/2950721
    library(fs)
    rdsFilesFolder <- path("rdsFiles")
    saveRDSobjects <- paste0("./", rdsFilesFolder, "/", xtsObjects, ".Rds")
    
    for (i in seq_along(xtsObjects)) {
      saveRDS(get(xtsObjects[i]), file = saveRDSobjects[i])
    }
    

    System used:

    • R version: 4.1.1 (2021-08-10)
    • RStudio version: 1.4.1717
    • OS: macOS Catalina version 10.15.7