'Replacing NA with 0 in columns that contain a substring in the column name

Let's say I had a data frame and I wanted to replace NA's with 0's only in columns that contained a specific string in the column name.

Let's call the dataframe df, the columns are numeric type, and the string "keyword".

i.e., a column name would be, "Column1keyword", etc.

How can I do this?

I've tried this and it didn't work:

 df %>%
    mutate(across(where(~ colnames.is.numeric(.x) && 'keyword' %in% colnames.x), replace_na, 0))
 
r


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source