Combine list of tibble tables if they have the same columns

Viewed 82

I have data of the form

[[1]] 
   a b c
1  3 4 8 
[[2]] 
   d e f
1  6 7 9 
[[3]] 
   g h i
1  1 4 5 
[[4]] 
   a b c
1  9 5 2 
[[5]] 
   d e f
1  5 8 0

I want to combine this to

[[1]]
  a b c
1 3 4 8
2 9 5 2
[[1]]
  d e f
1 6 7 9
2 5 8 0
[[3]]
  g h i
1 1 4 5

That is, I want to rbind the tibble tables in a list if they have the same column names. Could someone help me out? Kind regards.

2 Answers

One option could be:

lapply(split(lst, sapply(lst, function(x) toString(names(x)))), function(y) do.call(rbind, y))

$`a, b, c`
     a b c
[1,] 3 4 8
[2,] 9 5 2

$`d, e, f`
     d e f
[1,] 6 7 9
[2,] 5 8 0

$`g, h, i`
     g h i
[1,] 1 4 5

Or a more succinct option (proposed by @Ronak Shah):

tapply(lst, sapply(lst, function(x) toString(names(x))), function(x) do.call(rbind, x))

It's pretty messy but it may works

x <- unique(lapply(dummy, function(x) names(x)))
y <- lapply(dummy, function(x) names(x))
z <- match(y, x)
res <- vector(mode = "list", length = 3)
for (i in 1:length(z)) {
  res[[z[i]]] <- rbind(res[[z[i]]], dummy[[i]])
  
}

[[1]]
     a b c
[1,] 3 4 8
[2,] 9 5 2

[[2]]
     d e f
[1,] 6 7 9
[2,] 5 8 0

[[3]]
     g h i
[1,] 1 4 5
Related