Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading