Combining elements of list of lists by index

前端 未结 3 1283
长发绾君心
长发绾君心 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)
    

提交回复
热议问题