这是我希望的一些数据和最终结果。我有dfs的数量(示例有2),我想将它们组织为列表。示例更好地解释了它:
names <- as.yearmon(seq(as.Date("2010-01-01"), to=as.Date("2010-05-01"), by="month"))
names
df1 <- data.frame(X1 = c(1,2,3,4,5), X2 = c(1,2,3,4,5), X3 = c(1,2,3,4,5))
rownames(df1) <- names
df2 <- data.frame(Y1 = c(10,20,30,40,50), Y2 = c(10,20,30,40,50), Y3 = c(10,20,30,40,50))
rownames(df2) <- names
FullList <- list()
length(FullList) <- 5
names(FullList) <- names
FullList[[1]][[1]] <- df1[match(names(FullList)[1], rownames(df1)), ]
FullList[[1]][[2]] <- df2[match(names(FullList)[1], rownames(df2)), ]
FullList[[2]][[1]] <- df1[match(names(FullList)[2], rownames(df1)), ]
FullList[[2]][[2]] <- df2[match(names(FullList)[2], rownames(df2)), ]
FullList[[3]][[1]] <- df1[match(names(FullList)[3], rownames(df1)), ]
FullList[[3]][[2]] <- df2[match(names(FullList)[3], rownames(df2)), ]
FullList[[4]][[1]] <- df1[match(names(FullList)[4], rownames(df1)), ]
FullList[[4]][[2]] <- df2[match(names(FullList)[4], rownames(df2)), ]
FullList[[5]][[1]] <- df1[match(names(FullList)[5], rownames(df1)), ]
FullList[[5]][[2]] <- df2[match(names(FullList)[5], rownames(df2)), ]
因此,从2个或更多数据框结束列表列表,通用名称作为主列表名称。最终结果应该看起来像FullList
,实现这一目标的最佳方法是什么?
答案 0 :(得分:0)
这应该可以达到要求,但我同意Vlo这似乎是一个笨拙的数据结构:
lapply( names, function(nm) {
list( df1[ nm == rownames(df1), ,drop=FALSE],
df2[ nm == rownames(df2), ,drop=FALSE]) ) }
答案 1 :(得分:-2)
一个简单的循环可以为你工作。
for (listrow in 1:5) {
for (dataframe in 1:2) {
eval(parse(text=paste("FullList[[",listrow,"]][[",dataframe,"]] <- df",dataframe,"[match(names(FullList)[",listrow,"], rownames(df",dataframe,")), ]",sep="")))
}
}
此循环执行以下命令
for (listrow in 1:5) {
for (dataframe in 1:2) {
print(paste("FullList[[",listrow,"]][[",dataframe,"]] <- df",dataframe,"[match(names(FullList)[",listrow,"], rownames(df",dataframe,")), ]",sep=""))
}
}
[1] "FullList[[1]][[1]] <- df1[match(names(FullList)[1], rownames(df1)), ]"
[1] "FullList[[1]][[2]] <- df2[match(names(FullList)[1], rownames(df2)), ]"
[1] "FullList[[2]][[1]] <- df1[match(names(FullList)[2], rownames(df1)), ]"
[1] "FullList[[2]][[2]] <- df2[match(names(FullList)[2], rownames(df2)), ]"
[1] "FullList[[3]][[1]] <- df1[match(names(FullList)[3], rownames(df1)), ]"
[1] "FullList[[3]][[2]] <- df2[match(names(FullList)[3], rownames(df2)), ]"
[1] "FullList[[4]][[1]] <- df1[match(names(FullList)[4], rownames(df1)), ]"
[1] "FullList[[4]][[2]] <- df2[match(names(FullList)[4], rownames(df2)), ]"
[1] "FullList[[5]][[1]] <- df1[match(names(FullList)[5], rownames(df1)), ]"
[1] "FullList[[5]][[2]] <- df2[match(names(FullList)[5], rownames(df2)), ]"