BGR
BGR

Reputation: 23

how to merge two lists in R based on key value

How to merge two lists in R based on "business_id" and "type" variables. Tried a few options but they did not work including converting them into dataframes and trying to merge them using merge function.

The lists are

LIST1
$ :List of 5
  ..$ business_id  : chr "ABC"
  ..$ full_address : chr "DEF"
  ..$ hours        : chr "4-6PM"
  ..$ open         : logi TRUE
  ..$ type         : chr "business"

LIST2
$ :List of 3
  ..$ checkin_info:List of 3
  .. ..$ 7-6 : num 1
  .. ..$ 15-0: num 1
  .. ..$ 15-3: num 1
  ..$ type        : chr "business"
  ..$ business_id : chr "ABC"

The result should be

MERGED LIST $ :List of 6 ..$ business_id : chr "ABC" ..$ full_address : chr "DEF" ..$ hours : chr "4-6PM" ..$ open : logi TRUE ..$ type : chr "business" ..$ checkin_info:List of 3 .. ..$ 7-6 : num 1 .. ..$ 15-0: num 1 .. ..$ 15-3: num 1

Upvotes: 1

Views: 1809

Answers (1)

JasonAizkalns
JasonAizkalns

Reputation: 20463

You have still not provided a reproducible example -- see the link above. However, here is a reproducible example to illustrate the concepts at the heart of your question:

list1 <- list(business_id = 1:10,
              type = letters[1:10],
              values_1 = rnorm(10, 1))
# List of 3
# $ business_id: int [1:10] 1 2 3 4 5 6 7 8 9 10
# $ type       : chr [1:10] "a" "b" "c" "d" ...
# $ values_1   : num [1:10] 1.346 1.01 0.664 0.495 1.678 ...

list2 <- list(business_id = 5:14,
              type = letters[5:14],
              values_2 = rpois(10, 50))
# List of 3
# $ business_id: int [1:10] 5 6 7 8 9 10 11 12 13 14
# $ type       : chr [1:10] "e" "f" "g" "h" ...
# $ values_2   : int [1:10] 49 45 52 48 53 49 43 49 49 54

merge(list1, list2, by = c("business_id", "type"), all = TRUE)

#    business_id type    values_1 values_2
# 1            1    a  1.34647449       NA
# 2            2    b  1.00967581       NA
# 3            3    c  0.66401918       NA
# 4            4    d  0.49516496       NA
# 5            5    e  1.67790930       49
# 6            6    f  1.10751253       45
# 7            7    g  3.51306102       52
# 8            8    h  2.05527040       48
# 9            9    i  0.08864909       53
# 10          10    j -1.03377394       49
# 11          11    k          NA       43
# 12          12    l          NA       49
# 13          13    m          NA       49
# 14          14    n          NA       54

Upvotes: 1

Related Questions