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

How to change a value based on a condition in other column in R?

I want to change the values in a column based on another column.

If terminate_dyad 0 or NA then type.of.termination must be 0. If terminate_dyad 1 then type.of.termination must keep the value it has.

I tried to do that with case_when like that:

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

df %>%
  mutate(type.of.termination = case_when(terminate_dyad == 0 ~ 0))

However, I couldn’t figure out to change NA to 0, and keep to values if terminate_dyad == 1.

enter image description here

Thank you in advance.

>Solution :

You can just use ifelse():

df %>%
  mutate(type.of.termination = ifelse((is.na(terminate_dyad) | terminate_dyad == 0), 0, terminate_dyad))

Which returns:

# A tibble: 15 × 3
   dyadid terminate_dyad type.of.termination
    <dbl>          <dbl>               <dbl>
 1      1              0                   0
 2      3              0                   0
 3      3              0                   0
 4      3              0                   0
 5      3              0                   0
 6      3              0                   0
 7      4              0                   0
 8      4              0                   0
 9      4              0                   0
10      7              1                   1
11      7              0                   0
12      7              0                   0
13      7              1                   1
14     11              1                   1
15     12              1                   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