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 can I assign NA?

I use the mtcars dataframe and I use the following code to assign NA to all the values of columns drat and wt <=3.

df <- mtcars %>%
mutate(across(c(drat, wt), ~ifelse(.x<=3, NA, .x)))

How can I modify the code in a way that let me to assign NA also to the values of the column qsec if the value of drat or wt in the same row is <=3? At the end I want that each row where drat or wt is NA has NA also in the column qsec. Thanks

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 :

We may use if_any on the columns that are changed to NA to return a logical vector to replace values in ‘qsec’

library(dplyr)
mtcars1 <- mtcars %>%
      mutate(across(c(drat, wt), ~ifelse(.x<=3, NA, .x)),
    qsec = ifelse(if_any(c(drat, wt), is.na), NA, qsec))

-output

> head(mtcars1)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90    NA    NA  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90    NA    NA  0  1    4    4
Datsun 710        22.8   4  108  93 3.85    NA    NA  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105   NA 3.460    NA  1  0    3    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