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

Replace specific values in data frame in R

Below you can see my data.

df <- data.frame(
  R1 = c("EFTA : 0 / BAA/GBR : 0 / ES : 2", "10","EFTA : 0 / BAA/GBR : 0 / ES : 2","NA"),
  R2 = c("-", "EFTA : 0 / BAA/GBR : 0 / ES : 2","NA","CEFTA : 0 / MSA/GB : 0 / TR : 0")
)

enter image description here

Now I want to replace value from column R1 into column R2, but only if values in R2 are "-" or "NA". Final output that I expect is shown in table below.

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

enter image description here

So please can anybody help me to solve this ?

>Solution :

library(dplyr)

df |>
  mutate(R2 = replace(R2, R2 %in% c("-", "NA"), NA),
         R2 = coalesce(R2, R1),
         R1 = ifelse(R1 == R2, "", R1))

By using replace to turn those values into NA, we can then use coalesce to replace NA values when there is a value in R1.

Output

  R1                              R2
1    EFTA : 0 / BAA/GBR : 0 / ES : 2
2 10 EFTA : 0 / BAA/GBR : 0 / ES : 2
3    EFTA : 0 / BAA/GBR : 0 / ES : 2
4 NA CEFTA : 0 / MSA/GB : 0 / TR : 0
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