我不确定 OP 的真正目的导致他考虑创建一个 3-D 数组,为此他需要包含相同行数的列表的所有数据帧。
但是,无论是什么原因,都可以使用lapply 来实现。请注意 lengths 函数在包含数据框的列表上无法正常工作。由于lengths 函数只返回列表中包含的每个数据框中的列数。
因此,方法是首先找到mylist 中包含的数据框中的最大行数。然后遍历每个数据帧以将其行扩展到最大行数。
# Find maximum row across all data frames in mylist
maxrow <- max(sapply(mylist, nrow))
# Iterate over and increase the row count to maxrow
mylist_mod <- lapply(mylist, function(x,nRow){
if(nrow(x) < nRow){
x[(nrow(x)+1):nRow,] <- NA
}
x
}, nRow = maxrow)
mylist_mod
# $df1
# one two three
# 1 101 111 131
# 2 102 112 132
# 3 103 113 133
# 4 NA NA NA
# 5 NA NA NA
#
# $df2
# one two three
# 1 201 211 231
# 2 202 212 232
# 3 NA NA NA
# 4 NA NA NA
# 5 NA NA NA
#
# $df3
# one two three
# 1 301 311 331
# 2 302 312 332
# 3 303 313 333
# 4 304 314 334
# 5 305 315 335
样本数据:
df1 <- data.frame(one = 101:103, two = 111:113, three = 131:133)
df2 <- data.frame(one = 201:202, two = 211:212, three = 231:232)
df3 <- data.frame(one = 301:305, two = 311:315, three = 331:335)
mylist <- list(df1 = df1, df2 = df2, df3 = df3)
mylist
# $df1
# one two three
# 1 101 111 131
# 2 102 112 132
# 3 103 113 133
#
# $df2
# one two three
# 1 201 211 231
# 2 202 212 232
#
# $df3
# one two three
# 1 301 311 331
# 2 302 312 332
# 3 303 313 333
# 4 304 314 334
# 5 305 315 335