3

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!

markus
  • 25,843
  • 5
  • 39
  • 58
Nikhil Gopal
  • 107
  • 3
  • 6
  • 11

3 Answers3

4

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
markus
  • 25,843
  • 5
  • 39
  • 58
  • 1
    Quick question though, what exactly is this line doing? `Stocks <- vector("list", length(companies))` what is `"list"` supposed to mean here? – Nikhil Gopal Oct 13 '18 at 10:36
  • @NikhilGopal This creates an empty list of length 5 (the length of companies). `Stocks` allocates the space for the output. This more efficiency than growing a vector. `vector()` has two arguments: the type of the vector (“logical”, “integer”, “double”, “character”, etc) and the length of the vector. – markus Oct 13 '18 at 10:46
1

In my version of quantmod (0.4.0) it was necessary to set env=NULL in the functions' parameters, then the entire data frame is returned

TarangP
  • 2,711
  • 5
  • 20
  • 41
-1

Use the following argument as getSymbols(i, auto.assign=FALSE)

  • I did this but now I only get one value in each index of `Stocks`, it doesn't save the entire dataframe to index 1 :/ – Nikhil Gopal Oct 13 '18 at 10:08