I have several existing data.frame
objects that need to be updated from the Internet. However, as the updates have the same names as the mentioned existing objects, I put the updates in a separate environment also as data.frame
objects.
Then, the idea is to append the updates to the existing data.frame
objects. But I don't see how I can do that iteratively (i.e., in a loop?) with rbind
from one environment to GlobalEnv
(or another environment, for that matter).
Also, I did not put them here, but there will be several other data.frame
objects (with other names) that will in the GlobalEnv
(or the environment where they will be loaded).
Here below is a piece of code that should be reproducible (with comments and links to the sources):
library(quantmod)
# Load ticker data from 2020-01-01 till 2021-02-02
tickers <- c("NKLA", "MPNGF", "RMO", "JD", "MSFT")
getSymbols.yahoo(tickers, auto.assign = TRUE, env = globalenv(),
from = "2020-01-01", to = "2021-02-02")
# Close all Internet connections as a precaution
# https://stackoverflow.com/a/52758758/2950721
closeAllConnections()
# Find xts objects
xtsObjects <- names(which(unlist(eapply(.GlobalEnv, is.xts))))
# Convert xts to data.frame
# https://stackoverflow.com/a/69246047/2950721
for (i in seq_along(xtsObjects)) {
assign(xtsObjects[i], fortify.zoo(get(xtsObjects[i])))
}
# Redo the previous process but in separate environment for updated
# values of the same tickers (comments and sources are not repeated)
symbolUpdates.env <- new.env()
getSymbols.yahoo(tickers, auto.assign = TRUE, env = symbolUpdates.env,
from = "2021-02-03")
closeAllConnections()
symbolUpdatesXtsObjects <- names(which(unlist(eapply(symbolUpdates.env,
is.xts))))
for (i in seq_along(symbolUpdatesXtsObjects)) {
assign(envir = symbolUpdates.env, symbolUpdatesXtsObjects[i],
fortify.zoo(get(symbolUpdatesXtsObjects[i],
envir = symbolUpdates.env)))
}
# Find ```data.frame``` objects both in ```GlobalEnv``` and
# ```symbolUpdates.env```
globalEnvDataframeObjects <- names(which(unlist(eapply(.GlobalEnv,
is.data.frame))))
symbolUpdatesDataframeObjects <- names(which(unlist(eapply(symbolUpdates.env,
is.data.frame))))
# This rbind definitely does not work!!!
for (i in seq_along(globalEnvDataframeObjects)) {
rbind(envir = .GlobalEnv, globalEnvDataframeObjects[i], envir =
symbolUpdates.env, symbolUpdatesDataframeObjects[i])
}
My questions:
- With preferably no additional packages than the basic
R
ones, what piece of code can iteratively appendsymbolUpdatesDataframeObjects
to the correspondingglobalEnvDataframeObjects
? - Would the code be the same should
globalEnvDataframeObjects
be in another environment (i.e., not.GlobalEnv
, but a "sub-environment" likesymbolUpdates.env
)?- If not, what would change?
- Is there a better/wiser approach than the one I'm trying to use?
Thanks in advance.
Systems used:
- R version: 4.1.1 (2021-08-10)
- RStudio version: 1.4.1717
- OS: macOS Catalina version 10.15.7 and macOS Big Sur version 11.6