[英]Rbind corresponding elements in two or more lists in R
I have 3 lists, each with 500 elements. 我有3个列表,每个列表包含500个元素。 Here for demonstrative purposes, I have 2 lists with 1 element each:
这里出于说明目的,我有2个列表,每个列表1个元素:
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. 我的目标是将列表1中的第一个元素与列表2和3中的第一个元素绑定。然后,将列表1中的第二个元素与列表2和3中的第二个元素绑定。以此类推。
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.
我有a和b。 I want to obtain C.
我想获得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"))
Assuming length of a
and b
is the same we can do 假设
a
和b
长度相同,我们可以做
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. seq_along
生成从1到对象长度的序列。 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. 作为
length(a)
为2。因此,我们rbind
由一个数据帧一个rbind(a[[1]], b[[1]])
然后再rbind(a[[2]], b[[2]])
等。 lapply
ensures the final output is a list. lapply
确保最终输出是列表。
Just try the map2 function : 只需尝试map2函数:
purrr::map2(a,b,rbind) -> d
identical(c,d)
# [1] TRUE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.