In a dataframe we have:
| Column A | Column B | Column C |
|---|---|---|
| E | 1 | 3 |
| F | 2 | 2 |
| G | 3 | 1 |
I would like to create a Column D based on the following logic: match each column C value with column B and return the value of Column A that corresponds to the position of the matched value.
in this case it would look like this:
| Column A | Column B | Column C | Column D |
|---|---|---|---|
| E | 1 | 3 | G |
| F | 2 | 2 | F |
| G | 3 | 1 | E |
I have tried the following:
data<-data %>%
mutate(D = case_when(C%in%B~A))
but it returns the value of column A that matches column B and not column C.
>Solution :
You can use match,
df$ColumnD <- df$ColumnA[match(df$ColumnC, df$ColumnB)]
#[1] "G" "F" "E"
Or in dplyr
library(dplyr)
df %>%
mutate(ColumnD = ColumnA[match(ColumnC, ColumnB)])
ColumnA ColumnB ColumnC ColumnD
1 E 1 3 G
2 F 2 2 F
3 G 3 1 E
DATA
dput(df)
structure(list(ColumnA = c("E", "F", "G"), ColumnB = 1:3, ColumnC = 3:1), class = "data.frame", row.names = c(NA,
-3L))