Search code examples
rdataframextszooquantmod

R: Converting output from getSymbols() to data frame in one command without calling the object name explicitly


I would like to to convert output from the getSymbols in quantmod package to a data frame. Presently I achieve that with the following code.

Data <- new.env()
getSymbols(Symbols = "EUR/USD", src = "oanda", from = "2005-01-01", 
    to = "2006-01-01", env = Data)
test <- as.data.frame(Data$EURUSD)
head(test)

Ideally, I would like to shorten this code to something on the lines:

test <- as.data.frame(getSymbols(Symbols = "EUR/USD", 
   src = "oanda", from = "2005-01-01", to = "2006-01-01"))

But this doesn't work as it should:

> head(test)
  getSymbols(Symbols = "EUR/USD", src = "oanda", from = "2005-01-01", to = "2006-01-01")
1                                                                                 EURUSD

Ideally, I would like to avoid referring to the pair EUR/USD when working with the data as in future I will be working to make this component dynamic so having to type test <- as.data.frame(Data$EURUSD) spoils the fun. My ideal code, would work like that:

test <- as.data.frame(getSymbols(Symbols = *user input*, 
   src = "oanda", from = "2005-01-01", to = "2006-01-01"))

At the moment I'm not necessairly interested in the user input but in coercing quantmod output to data frame without the need to call the quantmod object name.


Solution

  • You can try something like this:

    userInput="EUR/USD"
    test<-as.data.frame(getSymbols(Symbols = userInput, 
        src = "oanda", from = "2005-01-01",to = "2006-01-01", env = NULL))
    

    Setting the env to NULL results in no creating the data in the environment and returning it.