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

蓝咒 提交于 2021-02-05 06:42:26

问题


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?


回答1:


An option is Map from base R

Map(rbind, b, a)



回答2:


Or you can try:

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

Assuming length(a) == length(b)




回答3:


One option is to use the purrr package.

library(purrr)

map2(b, a, rbind)


来源:https://stackoverflow.com/questions/58654257/how-to-apply-a-function-between-the-elements-of-2-lists-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!