Arrays 将不同长度的数据帧列表转换为数组

Arrays 将不同长度的数据帧列表转换为数组,arrays,r,list,dataframe,Arrays,R,List,Dataframe,我目前有一个7个数据帧的列表,每个数据帧有24列,但行数不同。我想将列表转换为三维数组,但我不能,因为列表中的所有组件都没有相同的维度。我有 一个数据帧有60行,4个数据帧有59行,2个数据帧有58行 当我尝试laply(mylist,unlist)时,我得到以下消息:错误:结果必须具有相同的维度 有没有办法将这些数据帧放入数组中?我如何才能将NAs放在其他6个数据帧的末尾,以使它们达到60行 我不确定OP的真正目的,这导致他考虑创建一个3-D数组,他需要包含相同行数的列表的所有数据帧 但是,无

我目前有一个7个数据帧的列表,每个数据帧有24列,但行数不同。我想将列表转换为三维数组,但我不能,因为列表中的所有组件都没有相同的维度。我有 一个数据帧有60行,4个数据帧有59行,2个数据帧有58行

当我尝试laply(mylist,unlist)时,我得到以下消息:错误:结果必须具有相同的维度


有没有办法将这些数据帧放入数组中?我如何才能将NAs放在其他6个数据帧的末尾,以使它们达到60行

我不确定OP的真正目的,这导致他考虑创建一个
3-D
数组,他需要包含相同行数的列表的所有数据帧

但是,无论原因是什么,都可以通过
lappy
实现。请注意,
length
函数在包含数据帧的列表上不能正常工作。As
length
函数只返回列表中包含的每个数据帧中的列数

因此,方法是首先查找
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
#查找mylist中所有数据帧的最大行数

maxrow这将为您提供最基本的解决方案:
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