使用 for 循环创建数组列表

Creating arraylist using for loop

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

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

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"))
}

现在,我想将每个股票数据添加到一个数组列表中,所以我尝试了这样的操作:

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"

我在pipe函数后给出的代码有问题吗?

只需使用 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:
.....