Maximilian
Maximilian

Reputation: 4229

How to insert (merge) list into list

I searched SO throughout but could not find solution to this.

Here is example:

m1 <- data.frame(matrix(1:4, nrow = 2, ncol = 2))
m2 <- data.frame(matrix(9:14, nrow = 3, ncol = 2))
mlist <- list(m1, m2)

b1 <- c(1,-1)
b2 <- c(1,-1,1)
blist <- list(b1, b2)

Desired result:

[[1]]
   X1 X2  new
1  1  3   1
2  2  4  -1

[[2]]
  X1 X2   new
1  9 12   1
2 10 13  -1
3 11 14   1

Upvotes: 1

Views: 36

Answers (1)

David Arenburg
David Arenburg

Reputation: 92282

You could simply combine Map and cbind (somewhat similar to @hrbrmstr comment I guess)

Map(cbind, mlist, new = blist)
# [[1]]
#   X1 X2 new
# 1  1  3   1
# 2  2  4  -1
# 
# [[2]]
#   X1 X2 new
# 1  9 12   1
# 2 10 13  -1
# 3 11 14   1

Upvotes: 5

Related Questions