Rbind corresponding elements in two or more lists in R

会有一股神秘感。 提交于 2019-12-02 18:08:04

问题


I have 3 lists, each with 500 elements. Here for demonstrative purposes, I have 2 lists with 1 element each:

structure(list(timeseries = c(1, 7, 59), t = c(1, 3, 7)), .Names = c("timeseries", "t"), row.names = c(NA, 3L), class = "data.frame")   

structure(list(timeseries = c(5, 6, 7), t = c(8, 9, 10)), .Names = c("timeseries", "t"), row.names = c(NA, 3L), class = "data.frame") 

My aim is to rbind the first element in list 1 with the first element in list 2 and 3. Then, the second element in list 1 with the second element in list 2 and 3. And so on.

In my example, I would end up with a list of this form

structure(list(timeseries = c(1,7,59,5, 6, 7), t = c(1,3,7,8, 9, 10)), .Names = c("timeseries", "t"), row.names = c(NA, 6L), class = "data.frame") 

How do I do this?

Thank you!

****EDIT*** Improved example of the intended outcome. I have a and b. I want to obtain C.

a<-list(structure(list(timeseries = c(1, 7, 59), t = c(1, 3, 7)), .Names = c("timeseries", "t"), row.names = c(NA, 3L), class = "data.frame"),
structure(list(timeseries = c(1, 7, 59), t = c(1, 3, 7)), .Names = c("timeseries", "t"), row.names = c(NA, 3L), class = "data.frame"))


b<-list(structure(list(timeseries = c(2, 3, 5), t = c(2, 4, 6)), .Names = c("timeseries", "t"), row.names = c(NA, 3L), class = "data.frame"),
        structure(list(timeseries = c(60, 70, 80), t = c(20, 30, 40)), .Names = c("timeseries", "t"), row.names = c(NA, 3L), class = "data.frame"))


c<-list(structure(list(timeseries = c(1, 7, 59, 2,3, 5), t = c(1, 3, 7, 2, 4, 6)), .Names = c("timeseries", "t"), row.names = c(NA, 6L), class = "data.frame"),
        structure(list(timeseries = c(1, 7, 59, 60, 70, 80), t = c(1, 3, 7, 20, 30, 40)), .Names = c("timeseries", "t"), row.names = c(NA, 6L), class = "data.frame"))

回答1:


Assuming length of a and b is the same we can do

lapply(seq_along(a), function(x) rbind(a[[x]], b[[x]]))

#[[1]]
#  timeseries t
#1          1 1
#2          7 3
#3         59 7
#4          2 2
#5          3 4
#6          5 6

#[[2]]
#  timeseries  t
#1          1  1
#2          7  3
#3         59  7
#4         60 20
#5         70 30
#6         80 40

seq_along generates sequence from 1 to length of the object. If you do

seq_along(a) #you would get output as
#[1] 1 2

as length(a) is 2. So we rbind the dataframe one by one rbind(a[[1]], b[[1]]) first, then rbind(a[[2]], b[[2]]) and so on. lapply ensures the final output is a list.




回答2:


Just try the map2 function :

purrr::map2(a,b,rbind) -> d
identical(c,d)
# [1] TRUE


来源:https://stackoverflow.com/questions/52754511/rbind-corresponding-elements-in-two-or-more-lists-in-r

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