使用for循环创建arraylist

时间:2018-12-07 12:35:37

标签: r for-loop quantmod

我想创建某些股票价格数据的数组列表。

首先,我使用以下方法选择了一篮子股票:

tickers <- c("^GSPC","MSFT","INTC","NVDA","AAPL")

接下来,我使用for循环功能下载了价格数据:

for (i in 1:length(tickers)) {
  getSymbols(tickers[i],
             from = as.Date("2006-01-01"), to = as.Date("2009-12-31"))
}

现在,我想将每个股票数据添加到arraylist中,所以我尝试了类似的操作:

s <- list()
for (i in 1:length(tickers)) {
  getSymbols(tickers[i],
             from = as.Date("2006-01-01"), to = as.Date("2009-12-31")) %>%
             {. ->> s[[i]]}
}

但是输出似乎只给我列出了股票名称的列表:

  

[[1]] [1]“ GSPC”

     

[[2]] [1]“ MSFT”

     

[[3]] [1]“ INTC”

     

[[4]] [1]“ NVDA”

     

[[5]] [1]“ AAPL”

管道函数后给出的代码有问题吗?

1 个答案:

答案 0 :(得分:0)

只需使用lapply创建您的列表对象,并确保将选项auto.assign设置为FALSE。

library(quantmod)

tickers <- c("^GSPC","MSFT","INTC","NVDA","AAPL")

# Get the ticker data
s <- lapply(tickers, getSymbols, from = as.Date("2006-01-01"), to = as.Date("2009-12-31"), auto.assign = FALSE)

# name the list objects
names(s) <- tickers

str(s)
List of 5
 $ ^GSPC:An ‘xts’ object on 2006-01-03/2009-12-30 containing:
  Data: num [1:1006, 1:6] 1248 1269 1273 1273 1285 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:6] "GSPC.Open" "GSPC.High" "GSPC.Low" "GSPC.Close" ...
  Indexed by objects of class: [Date] TZ: UTC
  xts Attributes:  
List of 2
  ..$ src    : chr "yahoo"
  ..$ updated: POSIXct[1:1], format: "2018-12-07 15:01:48"
 $ MSFT :An ‘xts’ object on 2006-01-03/2009-12-30 containing:
.....