Creating an array from two different dataframes in R

Viewed 66

I have two data frames below:

c1a <- c("1a","1a","1a")
c1b <- c("1b","1b","1b")
c2a <- c("2a","2a","2a")
c2b <- c("2b","2b","2b")
c3a <- c("3a","3a","3a")
c3b <- c("3b","3b","3b")
df1 <- as.data.frame(rbind(c1a,c2a,c3a))
df2 <- as.data.frame(rbind(c1b,c2b,c3b))

I want to create an array with three 2*3 matrices, each matrix gets its first row from df1, and its 2nd row from df2. something like,

, , 1

     [,1] [,2] [,3]
[1,]    1a    1a    1a
[2,]    1b    1b    1b

, , 2

     [,1] [,2] [,3]
[1,]    2a    2a    2a
[2,]    2b    2b    2b

, , 3

     [,1] [,2] [,3]
[1,]    3a    3a    3a
[2,]    3b    3b    3b



array(c(rbind(c1a,c2a),rbind(c1b,c2b)), dim = c(2,3,2))

I am not sure how to get this for all rows of dataframes.

2 Answers

We could use asplit to split the dataset by row (MARGIN = 1), use Map to rbind the corresponding list elements and convert the list to array with simplify2array

simplify2array(unname(Map(rbind, asplit(df1, 1), asplit(df2, 1))))

-ouptut

, , 1

     V1   V2   V3  
[1,] "1a" "1a" "1a"
[2,] "1b" "1b" "1b"

, , 2

     V1   V2   V3  
[1,] "2a" "2a" "2a"
[2,] "2b" "2b" "2b"

, , 3

     V1   V2   V3  
[1,] "3a" "3a" "3a"
[2,] "3b" "3b" "3b"

Or may also bind the datasets together creating an 'id' column, get the sequence by 'id', and do the group_split which returns a list of tibbles. If we need to convert to array, change the tibble to data.frame and use simplify2array

library(dplyr)
library(data.table)
bind_rows(df1, df2, .id = 'id') %>%
     mutate(rn = rowid(id), id = NULL) %>% 
     group_split(rn, .keep = FALSE) 

Update: we could try this way:

df3 <- rbind(df1, df2)
row.names(df3) <- NULL

split(df3[order(df3[,1]),], rep(1:3, each=2))

Output:

$`1`
  V1 V2 V3
1 1a 1a 1a
4 1b 1b 1b

$`2`
  V1 V2 V3
2 2a 2a 2a
5 2b 2b 2b

$`3`
  V1 V2 V3
3 3a 3a 3a
6 3b 3b 3b

First answer: that was a first try: In base R we could first rbind and then subset by row numbers:

df3 <- rbind(df1, df2)
array1 <- df3[c(1,4),]
array2 <- df3[c(2,5),]
array3 <- df3[c(3,6),]

array1
array2
array3

output:

array1
    V1 V2 V3
c1a 1a 1a 1a
c1b 1b 1b 1b
> array2
    V1 V2 V3
c2a 2a 2a 2a
c2b 2b 2b 2b
> array3
    V1 V2 V3
c3a 3a 3a 3a
c3b 3b 3b 3b
Related