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.
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