Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

r - How to bind data tables from lists in nested list?

I have a nested list dt_list, which contains in itself lists: dt_list1, dt_list2, dt_list3. Each of these three lists contains data tables with same names: dt1, dt2, dt3. So I can get dt1 of dt_list1 like this:

dt_list[["dt_list1"]][["dt1"]]

It will give data table:

ID    timestamp     type
AA   2020-10-01    user
A1   2020-10-01    administrator
BA   2020-10-01    user

and

dt_list[["dt_list2"]][["dt1"]]

will give:

ID    timestamp     type
KB   2020-10-02    new_user
AA   2020-10-02    administrator
BB   2020-10-02    user

I want to bind columns ID and type to get:

ID    type
AA    user
A1    administrator
BA    user
KB    new_user
AA    administrator
BB    user

I want to bind like that all "dt1" data tables from all three sublists dt_list1, dt_list2, dt_list3 using data.table::rbindlist() function. Binding two of them can be done like this:

data.table::rbindlist(list(dt_list[["dt_list1"]][["dt1"]], dt_list[["dt_list2"]][["dt1"]]))

It will bind two necessary dataframes. But I want to bind all three with iteration, not one by one (because there can be not three sublists, but 20 and one by one is not efficient in that case). I think a function which will bind all data tables dt1 from all sublists is the best solution. data.table library must be used for that

question from:https://stackoverflow.com/questions/65902065/how-to-bind-data-tables-from-lists-in-nested-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use [[ in lapply and rbind the result and remove column 2 with [-2].

do.call(rbind, lapply(dt_list, "[[", "dt1"))[-2]
#           ID type
#dt_list1.1  1    a
#dt_list1.2  2    a
#dt_list2.1  1    b
#dt_list2.2  2    b
#dt_list3.1  1    c
#dt_list3.2  2    c

Data:

dt_list <- list(dt_list1 = list(dt1 = data.frame(ID=1:2, time=2, type="a"))
          , dt_list2 = list(dt1 = data.frame(ID=1:2, time=2, type="b"))
          , dt_list3 = list(dt1 = data.frame(ID=1:2, time=2, type="c")))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...