Home > Software engineering >  Combine list elements (containing data.frames) based on element names in r
Combine list elements (containing data.frames) based on element names in r

Time:01-28

Assume I have a list with 26 elements, with each element being named and containing a data.frame.

lst <- lapply(1:26, function(x) data.frame(AA = 1:5, BB = 1:5, CC = 1:5))
names(lst) <- letters

How do I combine only select (specified) elements from this list into a new combined object (in this case, a data.frame)?

  • Ex: Let's say I want to only combine elements named "m" and "o" into a single data.frame.

      AA BB CC
    m  1  1  1
    m  2  2  2
    m  3  3  3
    m  4  4  4
    m  5  5  5
    o  1  1  1
    o  2  2  2
    o  3  3  3
    o  4  4  4
    o  5  5  5
    

I know there's a simply way to do this using rbind with either one of the apply functions or do.call or similar, but my various combinations of efforts have failed, and similar posts I've been able to find have not helped.

CodePudding user response:

We may subset the list by named and use rbind with do.call

do.call(rbind, lst[c("m", "o")])

CodePudding user response:

Base R approach using do.call:

do.call(rbind, args = lst[names(lst) %in% c("m","o")])

Though, it creates a bit of a messy bunch of numbered row names:

    AA BB CC
m.1  1  1  1
m.2  2  2  2
m.3  3  3  3
m.4  4  4  4
m.5  5  5  5
o.1  1  1  1
o.2  2  2  2
o.3  3  3  3
o.4  4  4  4
o.5  5  5  5

This could be cleaned up in a second step using row.names

  • Related