Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare values beween 2 columns and return value of a third column

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading