1

I have three tibbles a,b,c in a vector first=c(a,b,c). I have another three tibbles in another vector second=c(d,e,f). How do I do a parallel cbind? So a should be cbinded with d, b with e, and c with f. I started out with something like

lapply(first,function(item){}) 

but I don't know how to take the second list into consideration in a "parallel" way.

Example-

a1<-data.frame(a=c(1,2),b=c(4,5))
a2<-data.frame(a=c(5,6),b=c(7,8))
a3<-data.frame(e=c(34,26),f=c(41,65))
a4<-data.frame(e=c(13,25),f=c(14,57))

I want to cbind a1 to a3, and a2 to a4 to produce

  a b  e  f
1 1 4 34 41
2 2 5 26 65

and

  a b  e  f
1 5 7 13 14
2 6 8 25 57
user17144
  • 428
  • 3
  • 18
  • 1
    `Map(cbind, first, second)` ? – Ronak Shah Feb 27 '20 at 04:44
  • @Ronak Shah Assuming each tibble has 2 columns, this cbinds the first column of a with the first column of d, the second column of a with the second column of d, and similarly for b and e, and for c and f. I want a to be cbinded with d, b with e, and c with f. I don't want to go down to the level of the constituent columns. Please see my edit. – user17144 Feb 27 '20 at 05:08
  • 1
    So `Map(cbind, list(a1, a2), list(a3 ,a4))` ? – Ronak Shah Feb 27 '20 at 05:13
  • @Ronak Shah Works. Thank you. What is the difference? – user17144 Feb 27 '20 at 05:16
  • I am not exactly sure about the structure of `first`, `second` but I think it is lists of lists? If you have more than these 4 dataframes and don't want to manually include them in a `list` we can also automate to get all the data in a list, divide them into halves and then `cbind` parallelly. – Ronak Shah Feb 27 '20 at 05:22
  • And how is that done? If it is not too much trouble, can you enhance your response below? first and second are lists of dataframes, and since a data frame is list, yes, lists of lists. – user17144 Feb 27 '20 at 05:30
  • I just added that information in another answer. Hope that answers. – Ronak Shah Feb 27 '20 at 05:59
  • @Ronak Shah Yes, it does. Thank you. Is there one comprehensive reference for all of these commonly used constructs? – user17144 Feb 27 '20 at 06:13

2 Answers2

2

We can create list of a1, a2 and a3, a4 and use Map to cbind them.

Map(cbind, list(a1, a2), list(a3 ,a4))

#[[1]]
#  a b  e  f
#1 1 4 34 41
#2 2 5 26 65

#[[2]]
#  a b  e  f
#1 5 7 13 14
#2 6 8 25 57

purrr equivalent is :

purrr::map2(list(a1, a2), list(a3 ,a4), cbind)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

If we have the character vectors for objects, use mget to return the values of the objects in a list and then use map2 to loop over the corresponding list elements and bind the columns with bind_cols

library(purrr)
library(dplyr)
map2(mget(first), mget(second), bind_cols)
akrun
  • 874,273
  • 37
  • 540
  • 662