【问题标题】:R rowbind nested list elements while having higher level list namesR rowbind nested list elements while having higher level list names
【发布时间】:2022-12-02 03:29:45
【问题描述】:

I have a nested list like L below. All lists have the same structure but their names are different. I would like to rowbind all data frames in a1 while having two additional columns to have higher level list names. I was able to do this with a few lines ... but there should be an easier way to do this maybe with package purrr. My desire is to have test4.

L=list(a=list(A=list(a1=data.frame(C1=1,C2=2),a2=20),B=list(a1=data.frame(C1=3,C2=4),a2=30)),
       b=list(C=list(a1=data.frame(C1=5,C2=6),a2=20),D=list(a1=data.frame(C1=7,C2=8),a2=30)))

# Take a1 i.e. first element in the last list
test=lapply(L,function(x) lapply(x,"[[",1))
# rbind
test2=lapply(test,function(x) as.data.frame(do.call(rbind.data.frame,x)))
# Add additional column
test3=lapply(test2, function(x) {x$List_2_Name=row.names(x); return(x)})
# rbind
test4=data.table::rbindlist(test3,idcol = "List_1_Name")

test4
   List_1_Name C1 C2 List_2_Name
1:           a  1  2           A
2:           a  3  4           B
3:           b  5  6           C
4:           b  7  8           D
> 

【问题讨论】:

    标签: r list data.table purrr


    【解决方案1】:

    This can be done using rrapply() in package rrapply (extension of base rapply()):

    rrapply::rrapply(L, how = "bind", options = list(namecols = TRUE))
    
    #>   L1 L2 a1.C1 a1.C2 a2
    #> 1  a  A     1     2 20
    #> 2  a  B     3     4 30
    #> 3  b  C     5     6 20
    #> 4  b  D     7     8 30
    

    【讨论】:

      猜你喜欢
      • 2019-04-08
      • 2022-12-01
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      • 2012-01-23
      相关资源
      最近更新 更多