1

Here are two dataframe. How is it possible to use te productid of the second to merge the two dataframe but the first dataframe contains more rows and in some of them there must be in text column NA

dframe1 = data.frame(sample = c("text1", "text2", "text3", "text4", "text5", "text6", "text7", "text8", "text9", "text10"), 
                     productid = c(33, 5, 33, 34, 12, 54, 22, 9, 45, 22),
                     manifucturerid = c(1, 1, 2, 2, 3, 4, 5, 6, 7, 7))
dframe2 = data.frame(productid = c(33, 33, 34, 54, 22, 45, 22), 
                     text = c("a,b", "a,b", "c,d", "e,f,g", "h,i,j,k", "l,m", "h,i,j,k"))

Example of expected output

dframe = data.frame(sample = c("text1", "text2", "text3", "text4", "text5", "text6", "text7", "text8", "text9", "text10"), productid = c(33, 5, 33, 34, 12, 54, 22, 9, 45, 22), 
                    manifucturerid = c(1, 1, 2, 2, 3, 4, 5, 6, 7, 7), 
                    text = c("a,b", "NA", "a,b", "c,d", "NA", "e,f,g", "h,i,j,k", "NA", "l,m", "h,i,j,k"))
kath
  • 7,624
  • 17
  • 32
Kkyr
  • 55
  • 7
  • 2
    Possible duplicate of [How to join (merge) data frames (inner, outer, left, right)?](https://stackoverflow.com/questions/1299871/how-to-join-merge-data-frames-inner-outer-left-right) – phiver Sep 30 '18 at 12:24
  • 1
    Try `merge(dframe1, unique(dframe2), by = "productid", all.x = TRUE)`. – markus Sep 30 '18 at 12:26

1 Answers1

0

You can use dplyr::left_join() by productid. Left join keeps all rows of dframe1 and adds the text to a new column when the product ids match.

library(dplyr)
dframe <- left_join(dframe1, dframe2, by = "productid")

#    sample productid manifucturerid    text
# 1   text1        33              1     a,b
# 2   text2         5              1      NA
# 3   text3        33              2     a,b
# 4   text4        34              2     c,d
# 5   text5        12              3      NA
# 6   text6        54              4   e,f,g
# 7   text7        22              5 h,i,j,k
# 8   text8         9              6      NA
# 9   text9        45              7     l,m
# 10 text10        22              7 h,i,j,k
Paul
  • 2,877
  • 1
  • 12
  • 28