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:
data.frame
as .Rds
file, but ended up writing code about .Rda
;save()
whereas saveRDS()
should have been used. Failing to do so, command readRDS
won't read corresponding files.My question:
.Rds
files?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: