Search code examples
rlistquantmod

How do I store data from getSymbols (quantmod library) to a list?


Here's the code I'm running

library(quantmod)
library(tseries)
Stocks={}
companies=c("IOC.BO","BPCL.BO","ONGC.BO","HINDPETRO.BO","GAIL.BO")
for(i in companies){
   Stocks[i]=getSymbols(i)
}

I'm trying to get a list of dataframes that are obtained from getSymbols to get stored in Stocks. The problem is that getSymbols directly saves the dataframes to the global environment Stocks only saves the characters in companies in the list.

How do I save the dataframes in the Global Environment to a list?

Any help is appreciated.. Thanks in advance!


Solution

  • Another option is lapply

    library(quantmod)
    Stocks <- lapply(companies, getSymbols, auto.assign = FALSE)
    Stocks <- setNames(Stocks, companies)
    

    from ?getSymbols

    auto.assign : should results be loaded to env If FALSE, return results instead. As of 0.4-0, this is the same as setting env=NULL. Defaults to TRUE


    Using a for loop you could do

    companies <- c("IOC.BO", "BPCL.BO", "ONGC.BO", "HINDPETRO.BO", "GAIL.BO")
    Stocks <- vector("list", length(companies))
    
    for(i in seq_along(companies)){
      Stocks[[i]] <- getSymbols(name, auto.assign = FALSE)
    }
    Stocks