0

Assume I have two lists with equal number of (and shaped) elements. I would like to cbind the two lists.

How would I do this?

Thanks

list1 <- list()
list2 <- list()
list_all <- list()

list1[[1]] <- matrix(c(1,2,3,4), nrow=2)
list1[[2]] <- matrix(c(4,5,6,7), nrow=2)

list2[[1]] <- matrix(c(1,2,3,4), nrow=2)
list2[[2]] <- matrix(c(4,5,6,7), nrow=2)

# combine both sets of matrices at the same time:
list_all <- cbind(list1, list2)

# wrong output
list_all

# combine individually:
list_all[[1]] <- cbind(list1[[1]], list2[[1]])
list_all[[2]] <- cbind(list1[[2]], list2[[2]])

# wrong output
list_all

# desired output
list_all[[1]] <-matrix(c(1,2,3,4,1,2,3,4),nrow=2)
list_all[[2]] <-matrix(c(4,5,6,7,4,5,6,7),nrow=2)

list_all 
Stata_user
  • 562
  • 3
  • 14

1 Answers1

1

Use Map :

list_all <- Map(cbind, list1, list2)

Or map2 in purrr :

list_all <- purrr::map2(list1, list2, cbind)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213