1

I have two data frames with two different dimensions :

1:

head(x)
   Year GDP_deflator
1  1825           NA
2  1826           NA
3  1827           NA
4  1828           NA
5  1829           NA
6  1829           NA
7  1830           NA
8  1830           NA
9  1830           NA
10 1831           NA

dim(x)
  1733    2

2:

head(dataDef)
   Year GDP_deflator
1  1825     1.788002
2  1826     1.884325
3  1827     2.016997
4  1828     1.802907
5  1829     1.781999
6  1830     1.866437
7  1831     1.960316
8  1832     2.029601
9  1833     1.880957
10 1834     1.845750

dim(dataDef)
 101   2

I would like to substitute values from dataDef$GDP_deflator column into x$GDP_deflator column conditioned on Year column. In other words, I would like the answer to be:

head (x)

   Year GDP_deflator
1  1825           1.788002
2  1826           1.884325
3  1827           2.016997
4  1828           1.802907
5  1829           1.781999
6  1829           1.781999
7  1830           1.866437
8  1830           1.866437
9  1830           1.866437
10 1831           1.960316

So the repeating years (i.e. 1830) get the same value, 1.866437. Any suggestions?

Best Regards

user1665355
  • 3,324
  • 8
  • 44
  • 84
  • Can we assume there are no duplicates in `x$Year` ? If so, a loop or `lapply` which does something like the following will work. (looping over row index...) `dataDef[i,2]<-x[which(x[1,]==dataDef[i,2],2]` – Carl Witthoft Nov 19 '12 at 12:37

2 Answers2

0

You want to merge the two data.frames. It's a many-to-one merge.

Ari B. Friedman
  • 71,271
  • 35
  • 175
  • 235
  • That's why it's a many-to-one match. Use the `all.x` argument. If you want code you should provide a [reproducible question](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Ari B. Friedman Nov 19 '12 at 12:31
0

One possibility is to use match:

x$GDP_deflator <- dataDef$GDP_deflator[match(x$Year, dataDef$Year)]
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168