flamenco
flamenco

Reputation: 2840

How to apply a function between the elements of 2 lists in R?

Imagine that you have these variables:

> a <- list(matrix(1:25, 5, 5, byrow = TRUE), matrix(31:55, 5, 5, byrow = TRUE))
> b <- list(rep(1, 5), rep(2, 5))
> a
[[1]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    6    7    8    9   10
[3,]   11   12   13   14   15
[4,]   16   17   18   19   20
[5,]   21   22   23   24   25

[[2]]
     [,1] [,2] [,3] [,4] [,5]
[1,]   31   32   33   34   35
[2,]   36   37   38   39   40
[3,]   41   42   43   44   45
[4,]   46   47   48   49   50
[5,]   51   52   53   54   55

> b
[[1]]
[1] 1 1 1 1 1

[[2]]
[1] 2 2 2 2 2

I want to end up with something like this:

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    1    2    3    4    5
[3,]    6    7    8    9   10
[4,]   11   12   13   14   15
[5,]   16   17   18   19   20
[6,]   21   22   23   24   25

     [,1] [,2] [,3] [,4] [,5]
[1,]    2    2    2    2    2
[2,]   31   32   33   34   35
[3,]   36   37   38   39   40
[4,]   41   42   43   44   45
[5,]   46   47   48   49   50
[6,]   51   52   53   54   55

So, it is like having a Python zip-like function and then apply rbind. Any idea?

Upvotes: 2

Views: 72

Answers (3)

akrun
akrun

Reputation: 887148

An option is Map from base R

Map(rbind, b, a)

Upvotes: 3

StupidWolf
StupidWolf

Reputation: 46908

Or you can try:

lapply(1:length(a),function(i)rbind(b[[i]],a[[i]]))

Assuming length(a) == length(b)

Upvotes: 2

prosoitos
prosoitos

Reputation: 7347

One option is to use the purrr package.

library(purrr)

map2(b, a, rbind)

Upvotes: 1

Related Questions