假设我在R中有一个包含大量元素的列表。它们的结构类似于下面的例子(SYMBOLX 1999,SYMBOLX 2000,SYMBOLY 1999,SYMBOLY 2000等)。我试图将每个符号放在一起(rbind),然后将整个符号组合成一个数据帧(cbind)。
现在,当我在2600个元素列表上执行此操作时,下面的代码似乎相当慢。任何人都可以提出一种更有效的方法来实现这一目标吗?
我在下面做了一个有希望重现的例子(实际值并不重要,现在只是随机的)。
symbols <- c("SYMBOLX","SYMBOLY")
first <- structure(list(`_id` = "123182914914", symbol = "SYMBOLX",
year = 1999, monthly = data.frame("COL2"=runif(10, -0.03, 0.03))),
.Names = c("_id", "symbol", "year", "monthly"))
second <-structure(list(`_id` = "123182914915", symbol = "SYMBOLX",
year = 2000, monthly = data.frame("COL2"=runif(10, -0.03, 0.03))),
.Names = c("_id", "symbol", "year", "monthly"))
third <- structure(list(`_id` = "123182914916", symbol = "SYMBOLY",
year = 1999, monthly = data.frame("COL2"=runif(10, -0.03, 0.03))),
.Names = c("_id", "symbol", "year", "monthly"))
fourth <- structure(list(`_id` = "123182914917", symbol = "SYMBOLY",
year = 2000, monthly = data.frame("COL2"=runif(10, -0.03, 0.03))),
.Names = c("_id", "symbol", "year", "monthly"))
big_list <- list(first,second,third,fourth)
unique_years <- unique(unlist(lapply(big_list, '[[', 'year')))
all_data <- vector(mode = "list", length = length(symbols))
for (i in 1:length(symbols)) {
xts_data <- do.call("rbind", lapply(big_list[((length(unique_years)*(i-1))+1):(length(unique_years)*i)], '[[', 'monthly'))
colnames(xts_data) <- symbols[i]
all_data[[i]] <- xts_data
}
# create final output combined dataframe
master_data <- do.call("cbind", lapply(all_data, function(x) x))