0

I have a dataframe:

title,text
title1,text1
title2,text2
title3,text3
title4,text4
title5,text5

and another one

text,stock
text2,40
text1,50
text5,30
text4,50

I want to merge this two dfs, the only common feature is the column text but the problem is that one row is missing of the second df and they have different order. How can I merge them in order to take an output like this:

title,text,stock
title1,text1,50
title2,text2,40
title3,text3,
title4,text4,50
title5,text5,30
Ster32
  • 415
  • 4
  • 10

1 Answers1

2

You can use merge

  merge(df1, df2, by='text', all=TRUE)
  #   text  title stock
  #1 text1 title1    50
  #2 text2 title2    40
  #3 text3 title3    NA
  #4 text4 title4    50
  #5 text5 title5    30

Or using the devel version of data.table

  library(data.table)#v1.9.5+
  setDT(df2)[df1, on='text']
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Is it possible to have the order of the first df in the data? – Ster32 Jul 26 '15 at 12:08
  • @Ster32 Looks like the `merge` output is the same as your expected one. Am i missing something? Or do you want to change the column order. In that case `res <- merge(df1, df2, ...); res[c(2,1,3)]` – akrun Jul 26 '15 at 12:12
  • @Ster32 Another option is `library(dplyr);left_join(df1, df2)` In the example you provided, all of these gives the same output. – akrun Jul 26 '15 at 12:15
  • yes that's why I have I accept the answer however testing it to the whole data I have I show in df common column there are also other words and I thought to ask you if it is possible to have the order of the first df. Just in case you know thank you – Ster32 Jul 26 '15 at 12:15
  • @Ster32 Try with `left_join` as in the comment above. It should provide the output as the same order as `df1` (not tested) – akrun Jul 26 '15 at 12:16