将具有不同列号和行号的数据帧列表转换为 R 中的 3 维数组

问题描述 投票:0回答:2
df1<-data.frame(ID=1:3,test=2:4,category=1)   
df2<-data.frame(ID=1:2,test=4:5,test1=2:3,category=2)
Mylist<-list(df1,df2)

我试过了

array1<-array(unlist(Mylist)) 

预期的结果是 array1 看起来像这样

array1[ , ,1]
      [,1]      [,2]        [,3]     
[1,] 1           2           1 
[2,] 2           3           1 
[3,] 3           4           1 
array1[ , ,2]
      [,1]      [,2]      [,3]      [,4]     
[1,]   1          4         2         2
[2,]   2          5         3         2

但是我不知道如何指定数组的维度,因为每个矩阵/数据框都有不同的列/行号。

谢谢你的帮助。

r arrays list 3d
2个回答
0
投票

一个策略可以使用

abind
.

  1. 我们确定列表中的最大行数和列数
  2. 用 NA 填充每个矩阵/df
  3. 最后,使用
    abind
  4. 将列表转换为3维数组
# given list
A1 <- matrix(runif(500), 25, 20)
A2 <- matrix(runif(483), 23, 21)
A3 <- matrix(runif(600), 24, 25)
MyList <- list(A1, A2, A3)

# 1. get max rows and cols:
max_rows <- max(sapply(MyList, nrow))
max_cols <- max(sapply(MyList, ncol))

# 2. pad with NA
MyList <- lapply(MyList, function(x) {
  rows_missing <- max_rows - nrow(x)
  cols_missing <- max_cols - ncol(x)
  padded <- matrix(NA, nrow = max_rows, ncol = max_cols)
  padded[1:nrow(x), 1:ncol(x)] <- x
  padded
})

# 3. get 3-dimensional array
array1 <- abind(MyList, along = 3)

0
投票

数组不能参差不齐。如果 a 是结果,则 a[,,1] 和 a[,,2] 必须具有相同的维度。有了这个警告,我们将每个数据框与另一个数据框的 ID 合并,以获得每个数据框的相同 ID,然后使用 bind_rows 获取相同的列,最后使用 abind 将它们放在一起。

library(abind)
library(dplyr)

Merge <- function(..., all = TRUE) merge(..., all = all)

L <- list(df1, df2)
IDs <- Reduce(Merge, lapply(L, function(x) x["ID"]))
DF <- bind_rows(lapply(L, Merge, IDs))
nid <- nrow(IDs)
abind(split(DF, rep(1:(nrow(DF) / nid), each = nid)), along = 3)

给予:

, , 1

     ID test category test1
[1,]  1    2        1    NA
[2,]  2    3        1    NA
[3,]  3    4        1    NA

, , 2

     ID test category test1
[1,]  1    4        2     2
[2,]  2    5        2     3
[3,]  3   NA       NA    NA

注意

如问题所示,输入是

df1<-data.frame(ID=1:3,test=2:4,category=1)
df2<-data.frame(ID=1:2,test=4:5,test1=2:3,category=2)
© www.soinside.com 2019 - 2024. All rights reserved.