0

I have a data set which looks like the following:

df1

The 'X19' is the row number of another data set. How can I merge these two data sets such that 'FNUMM' will be added to each row appears in 'X19'?

df2

Thanks.

eipi10
  • 91,525
  • 24
  • 209
  • 285
  • Please don't post an image of the data, but rather a sample of your data.frame(s) (e.g. post the output of `dput(head(DF,10))`). See [how to make a great reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – digEmAll May 06 '17 at 20:52
  • ..and possibly post both data.frame's. In your image I see just one, and honestly I don't understand what are you trying to accomplish... – digEmAll May 06 '17 at 20:53
  • Sry I don't really know how to post a sample... I'll just post another image of the dataframe. –  May 06 '17 at 20:56
  • 1
    Paste into your question the output of `dput(head(df1,10))` and `dput(head(df2,10))`. – eipi10 May 06 '17 at 20:58

2 Answers2

1

Try merge(df1, df2, by = 'X19'), where df1 and df2 are your two data frames.

biomiha
  • 1,358
  • 2
  • 12
  • 25
  • It says "Error in fix.by(by.x, x) : 'by' must specify a uniquely valid column". I guess that is because df1 and df2 do not have the same number of rows. –  May 06 '17 at 20:47
  • Or can you tell me if I can manipulate the df w/ less rows so that it has as many rows as the other df? –  May 06 '17 at 20:52
  • Kind of difficult to tell, since I can't reproduce your data or at least part of it to see what's going on. – biomiha May 07 '17 at 09:54
1

This is a merge where one of the keys is the rownames of one dataset. You can do this:

 cbind(df1, df2[, "FNUMM"][match(rownames(df1), df2$X19)])

Here is a reproducible example

df1 <- data.frame(ID=c(1L,1L,1L,1L,2L,2L,3L,3L), 
                 var=c(1:8), Smoke=c('No','No','Yes','No','No','No','Yes','No'))

df2 <- data.frame(X19=c(2,5,8), FNUMM=c('a','b','c'))

cbind(df1, df2[, "FNUMM"][match(rownames(df1), df2$X19)])
rafa.pereira
  • 13,251
  • 6
  • 71
  • 109