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

Combining matches function to select columns and replace NAs values in selected columns

I have a data frame that has multiple columns that start with the string ID, here is an example:

id_row  ID df_1 wsts (xc) ... ID df_2 ... ID df_3 ...
1   tc  2937.5 ... tc ... xk
2   tc  3048      xk     xk
3   NA 1323       ck     NA
4   xk  4245      NA     NA

… represent the numerical values between each ID column.

Between each ID column, I have multiple columns with numerical values. The main idea of my code is to select only columns that start with "ID" string in their column name.
Then, inside each of those columns I want to replace NAs values for the string "NULL".
This code is not working, return me the same df without replacing the NA values for the desired string.

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_2 %>%
     select(matches("^ID")) %>%
     replace_na(list(. = "NULL"))

Questions:

  • What is the issue with my current approach?

  • What do I need to change to reach my goal?

>Solution :

One way to do that is adding a mutate()

df <-data.frame(ID1=c("aa", "bb", NA, "dd"),
               v1=1:4,
               ID2=c(NA, "bb", NA, "dd"),
               v2=1:4)

df %>%
  mutate(across(.cols=matches("^ID"), 
                .fns=~replace_na(., "NULL")))

I used this post as inspiration Using replace_na with across in mutate

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