jeudi 4 août 2016

R - Match column by other columns in same data frame

In the following dataframe I want to create a new column called D2 that matches the corresponding A, B, or C column. For example, if D == A, I want D2 == A2.

A   A2  B   B2  C   C2  D
1   10  2   90  3   9   1
1   11  2   99  3   15  1
1   42  2   2   3   9   2
1   5   2   54  3   235 2
1   13  2   20  3   10  3
1   6   2   1   3   4   3

This is what I want the new data frame to look like:

A   A2  B   B2  C   C2  D   D2
1   10  2   90  3   9   1   10
1   11  2   99  3   15  1   11
1   42  2   2   3   9   2   2
1   5   2   54  3   235 2   54
1   13  2   20  3   10  3   10
1   6   2   1   3   4   3   4

I have succeeded in doing this with ifelse statements using dplyr, but because I am doing this with many columns, it gets tedious after a while. I was wondering if there is a more clever way to accomplish the same task.

library(dplyr)  

newdata <- olddata %>% mutate(D2=ifelse(D==A,A2,ifelse(D==B,B2,C2)))

Aucun commentaire:

Enregistrer un commentaire