rlist

list cbind with two list element in R


I have 2 lists:

a = list(data.frame(a = 1:10, b = 21:30), data.frame(a = 11:20, b = 31:40))
b = list(data.frame(c = letters[1:10]), data.frame(c = LETTERS[1:10]))

And I want to cbind automatically them so that the column c gets paired with each element in the a list.

This is what I expext (manually)

c = list(data.frame(a = 1:10, b = 21:30, c = letters[1:10]), data.frame(a = 11:20, b = 31:40, c = LETTERS[1:10]))

When trying this,

do.call(cbind, a, b)

I get

Error in if (quote) args <- lapply(args, enquote) : 
  the condition has length > 1

Expected output:

c
[[1]]
    a  b c
1   1 21 a
2   2 22 b
3   3 23 c
4   4 24 d
5   5 25 e
6   6 26 f
7   7 27 g
8   8 28 h
9   9 29 i
10 10 30 j

[[2]]
    a  b c
1  11 31 A
2  12 32 B
3  13 33 C
4  14 34 D
5  15 35 E
6  16 36 F
7  17 37 G
8  18 38 H
9  19 39 I
10 20 40 J

Solution

  • We can use Map()

    > Map("cbind", a, b)
    [[1]]
        a  b c
    1   1 21 a
    2   2 22 b
    3   3 23 c
    4   4 24 d
    5   5 25 e
    6   6 26 f
    7   7 27 g
    8   8 28 h
    9   9 29 i
    10 10 30 j
    
    [[2]]
        a  b c
    1  11 31 A
    2  12 32 B
    3  13 33 C
    4  14 34 D
    5  15 35 E
    6  16 36 F
    7  17 37 G
    8  18 38 H
    9  19 39 I
    10 20 40 J
    

    as long as a and b are of same length and their data frames are equal in row numbers.