Search code examples
rstringloopsquantmod

Change String into name to access dataframe (R)


it's the R-Beginner again.

I have the following problem: I have a vector containing strings which is used to get some Dataframes through quantmod's GetSymbols():

library(quantmod)
tickers = c("GOOG", "XOM", "GE", "KO", "F", "GS", "AIG", "HPQ", "WMT", "MSI")
n = length(tickers)



for (i in 1:n){
    getSymbols(Symbols = tickers[i], from=start, to=end, src="yahoo")

now my problem is the following: I want to access the specific dataframe within this loop and maybe extract the ".Close"-column of it in it's own vector. I tried the following (and several other tries):

   adress = tickers[i]
   price.[i]  = cbind(adress[,4])


}

But obviously it does not work because adress just is a string. So my question is, how can i convert the string into another datatype that this "function" adresses the dataframe created before by GetSymbols in a manner that the loop still works; My next question is if the iteration on price.[i] does work so that i have n vectors for that with each a different name?

The sense behind all this is to abstract the scripts i created so far that it does neither matter how many Symbols i have and that i don't have to do the work for each of them when i use for example dygraph or rCharts or whatever, which then will be finish of the script giving charts on all of the ticker's closing prices.

I hope that my language was understandable. I also excuse myself that this might be a dumb question as i am still an R-Beginner trying to get into this for my new work;

Thank you guys for reading and helping me. Have a nice day.


Solution

  • I agree that a list is the way to go. However I would avoid using a loop. Try this instead:

    tickers = c("GOOG", "XOM", "GE", "KO", "F", "GS", "AIG", "HPQ", "WMT", "MSI")
    getSymbols(tickers, from = start, end = end)
    

    If you want prices in a matrix:

    prices = do.call(merge, lapply(tickers, function(x) Cl(get(x)))
    names(prices) = tickers
    

    Or if you want prices as a vector:

    prices = lapply(tickers, function(x) get(x))
    names(prices) = tickers