【问题标题】:Convert a list of dataframes of different lengths to an array将不同长度的数据帧列表转换为数组
【发布时间】:2018-11-18 22:50:42
【问题描述】:

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

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

有没有办法将这些数据框放入一个数组中?我怎样才能将 NA 放在其他 6 个数据帧的末尾以使它们达到 60 行?

【问题讨论】:

标签: arrays r list dataframe


【解决方案1】:

我不确定 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 2020-10-09
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    相关资源
    最近更新 更多