dimanche 20 octobre 2019

Import values based on conditional statement from multiple columns in R

I am working on a data set that looks like the following:

ID        Year       VAR3
1         1990       NA
1         1991       NA
1         1992       NA
2         1990       NA
2         1991       NA
2         1992       NA
2         1993       NA
3         1990       NA
3         1992       NA
3         1993       NA

I am trying to pull from another data set some information on "VAR3". The problem is that the information on VAR 3 has different values per year separated by column, rather than row on the other data set. So it looks something like this.

ID             VAR 3 (1990)    VAR 3 (1991)    VAR 3 (1992)
1                  1                 1                1
2                  2                 1                2
3                  3                 2                5
4                  4                 1                1
5                  1                 3                3
6                  1                 1                1

What I want to do is import the values of VAR3 for a given year from the second data set into the first data set above, conditional on the ID and Year matching. So if I imported the 1990 data for example I want it to look like this afterwards:

ID        Year       VAR3
1         1990       1
1         1991       NA
1         1992       NA
2         1990       2
2         1991       NA
2         1992       NA
2         1993       NA
3         1990       3
3         1992       NA
3         1993       NA

Eventually, I want to important all of the VAR3 (so the same process for 1991 and 1992 columns for example) values from the different columns from the old dataset into the new data set conditioning on matching the ID and year of course. Is there a way I can do this? I have tried a bunch of different methods to no avail.

Thanks in advance for any suggestions and help!

Aucun commentaire:

Enregistrer un commentaire