1

So I'm heavily simplifying my actual problem, but I am trying to find a way to append values inside vectors from one list, to values in vectors in another list, and do it by name ( assuming the two lists are not ordered).So this is the setup to the problem ( the numbers themselves are arbitrary here):

Data1 <- list( c(1),c(2),c(3))
names(Data1) <- c("A", "B","C")

Data2 <- list(c(11), c(12), c(13))
names(Data2) <- c("B","A","C")

Now what Im trying to do, is find a way to get a third list - say Data3, so that calling Data3[["A"]] will give me the same result as calling c(1,12):

[1] 1 12

so >Data3 should give:

[1] 1 12
[2] 2 11
[3] 3 13

Essentially im looking to append many values from one list of vectors, to another list of vectors, and do it by names rather than order, if that makes sense. (I did think about trying some loops, but I feel like there should be another way that is simpler)

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
dvd280
  • 876
  • 6
  • 11

3 Answers3

2
nm = names(Data1)
setNames(lapply(nm, function(x){
    c(Data1[[x]], Data2[[x]])
}), nm)
#$A
#[1]  1 12

#$B
#[1]  2 11

#$C
#[1]  3 13
d.b
  • 32,245
  • 6
  • 36
  • 77
2
list(do.call("cbind", list(Data1, Data2)))
  [,1] [,2]
A 1    11  
B 2    12  
C 3    13  

If you don't mind your output to be a dataframe:

Data3 <- rbind(data.frame(Data1), data.frame(Data2))

Then Data3[["A"]] will give you:

[1]  1 12
Lennyy
  • 5,932
  • 2
  • 10
  • 23
2

We can use Map and arrange the elements of Data2 in the same order as Data1 (or vice versa) using names and then concatenate them.

Map(c, Data1, Data2[names(Data1)])

#$A
#[1]  1 12

#$B
#[1]  2 11

#$C
#[1]  3 13
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213