【发布时间】: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