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

Check if column data exists in column and return value of the another column in R

I want to check if values from column B exist in column A, and if yes and equal with the value in that row, create another column D, getting the value from column C (for the A on that row).

A B C D
a f 12 55
b a 23 12
c b 33 23
d c 1 33
e e 11 11
f d 55 1

This is what I have, but it’s not working as it should as it is setting the value of D by just checking if the value exists in column A and not comparing them.

  ifelse(df$B %in% df$A, df$C , NA)

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

>Solution :

You could also do:

transform(df1, D = setNames(C,A)[B])

  A B  C  D
1 a f 12 55
2 b a 23 12
3 c b 33 23
4 d c  1 33
5 e e 11 11
6 f d 55  1
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