I have two lists of dataframes that I want to combine, I have tried the following:
A <- data.frame(ID = c(1,2,3),
var1 = c(3,4,5),
var2 = c(6,3,2))
B <- data.frame(ID = c(1,2,3),
var1 = c(4,4,5),
var2 = c(6,7,3))
C <- data.frame(ID = c(1,2,3),
var1 = c(1,4,8),
var2 = c(9,2,3))
list1 <- list(A = A, B = B, C = C)
list2 <- list(A = A, B = B)
combined <- map2(list1, list2, full_join, by = 'ID')
This returns an error that the two lists are of different lengths. The only other way I have thought of is to add a blank dataframe to the second list so they are the same length.
Is it possible combine the two lists so that I get a single list where A1 has been joined with A2, B1 with B2, and C1 remains as it is?
Edit: Its been highlighted that I havent named the elements of the list, I have named them now
If we have named lists, then we could:
list1 <- list(A = A, B = B, C = C)
list2 <- list(A = A, B = B)
x12 <- intersect(names(list1), names(list2))
x1 <- setdiff(names(list1), names(list2))
x2 <- setdiff(names(list2), names(list1))
combined <- c(
map2(list1[ x12 ], list2[ x12 ], full_join, by = 'ID'),
list1[ x1 ],
list2[ x2 ])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With