当前位置: 动力学知识库 > 问答 > 编程问答 >

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

网友答案:

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)})
分享给朋友:
您可能感兴趣的文章:
随机阅读: