Home > Software engineering >  R: using the index inside a for loop
R: using the index inside a for loop

Time:10-23

I was wondering how I can use the index (i) of a "for loop" inside it. Especially with the "$-notation".

for (i in tickers){
 
  getSymbols(i, from = '2021-01-6',
             to = "2021-10-21",warnings = FALSE,
             auto.assign = TRUE)

  MA9 = mean(tail(i$i.Adjusted, n=9))
  
  print(MA9)
}

Thanks already for taking your time to read this!

CodePudding user response:

getSymbols function works for multiple tickers at the same time. You can use mget to get them in a list and since Adjusted value is the 6th column you can subset it and get the mean of last 9 values with sapply.

Here is an example with tickers c('QQQ','SPY').

library(quantmod)
tickers <- c('QQQ','SPY')

getSymbols(tickers, from = '2021-01-6',
           to = "2021-10-21",warnings = FALSE,
           auto.assign = TRUE)

sapply(mget(tickers), function(x) mean(tail(x[, 6], n=9)))

#    QQQ      SPY 
#366.1511 442.2178 
  • Related