Combining elements of list of lists by index

前端 未结 3 1284
长发绾君心
长发绾君心 2020-12-09 11:36

Consider the following list of lists:

lst = list(list(c(1,2), c(3,4)),list(c(5,6), c(7,8)),list(c(9,10), c(11,12)))

The list lst

相关标签:
3条回答
  • 2020-12-09 11:49

    I was looking for something along the lines of the OP's question... but with a list of data frames instead of vectors. In that case, slightly modifying @joran's answer above gives the desired result. Consider:

    mylist <- 
      lapply(1:2, function(y){
        df1 <- data.frame(a=y, b=y^2, c=y^3)
        df2 <- data.frame(d=y, e=y+1)
        return(list(df1=df1, df2=df2))
        }) 
    

    You can then re-combine the sub-list elements into separate data frames based on their common indexes:

    library(dplyr)
    mylist2 <- do.call(function(...) mapply(bind_rows, ..., SIMPLIFY=F), args = mylist)
    
    0 讨论(0)
  • 2020-12-09 12:06

    You can do:

    do.call(Map, c(c, lst))
    
    0 讨论(0)
  • 2020-12-09 12:06

    You're on the right track:

    do.call(function(...) mapply(c,...,SIMPLIFY = FALSE),args = lst)
    [[1]]
    [1]  1  2  5  6  9 10
    
    [[2]]
    [1]  3  4  7  8 11 12
    
    0 讨论(0)
提交回复
热议问题