Search code examples
rquantmod

R - For Cycle and Apply function (Quantmod)


Hy,

I have this data frame, I want download the data from Yahoo and Calculate Percent Change (Delt function in Quantmod)

View(Equity)

  Symbol
1      A
2     AA
3    AAC 

I made a cycle

m<-nrow(Equity)

for (i in 1:m) {

   EquityDF <- Equity[i,]
   Data<-getSymbols(EquityDF,src="yahoo")
   Delt[i]<-apply(EquityDF[,1:5], 2, function(x) Delt(x, k=1)*100)

}

But I received this error

Error in EquityDF[, 1:5] : incorrect number of dimensions

I know why this error appear because if I make

EquityDF

the output it is

"A"

how can I fix this ?

Thanks


Solution

  • This happens because EquityDF is still a character. To retrieve the corresponding data you must use get: get(EquityDF)[, 1:5]

    Additionally I'd suggest to call getSymbols only once, so that you retrieve all your needed data in a single call, thus your code can be simplified to:

    Equity <- data.frame(Symbol = c("A","AA","AAC"), stringsAsFactors = FALSE)
    getSymbols(Equity[, 1], src="yahoo")
    Delt <- lapply(mget(Equity[, 1]), function(y){
               apply(y[, 1:5], 2, function(x) Delt(x, k=1)*100)})