There is already a thread asking how to convert multiple xts
objects into as many data.frames here. Unfortunately, the solutions show how to do it for data that is being downloaded in .GlobalEnv
. Moreover, the first answer of mentioned thread suggests to create a new environment, download the objects into it, and transform everything inside with the following code: stocks <- eapply(dataEnv, as.data.frame)
.
However, this creates a large list stored in the variable stocks
, whereas I need the objects to remain discrete. Even when I run the code without generating a list (i.e., by just applying eapply(dataEnv, as.data.frame)
), nothing happens. This has been documented here. In order to update the original object, the answer to this question was to use a code that looks like this: NKLA <- fortify.zoo(NKLA)
. This solution, which by the way works, is ok for a few objects that can be done manually and I need to automatise the process.
In my case, the objects are already downloaded and some of the them are data.frames
, some are xts
objects, and there might even be other objects.
What I need is to find the xts
objects and transform them into data.frames
.
In order to find the xts
objects, I use the following code: xtsObjects <- which(unlist(eapply(.GlobalEnv, is.xts)))
, but applying xtsObjects <- fortify.zoo(xtsObjects)
only creates yet another object called xtsObjects
that contains, for example, 2 obs. of 2 variables (because there are 2 xts
objects in the environment).
For example, the following code (which should be reproducible) does not change the discrete xts
objects into discrete data.frames
:
library(quantmod)
library(zoo)
tickers <- c("TSLA", "RMO", "TSM", "PDD")
getSymbols.yahoo(tickers, auto.assign = TRUE, env = globalenv())
xtsObjects <- which(unlist(eapply(.GlobalEnv, is.xts)))
# This does not do anything:
for (i in 1:length(xtsObjects)) fortify.zoo(xtsObjects[i])
My question:
- What loop (or any code) could I use in order to simultaneously update the original already loaded/existing
xts
objects intodata.frame
objects?
System used:
- R version: 4.1.1 (2021-08-10)
- RStudio version: 1.4.1717
- OS: macOS Catalina version 10.15.7