R: How to create a is.a column for a list of given columns

Viewed 22

let's say I have the following tibble:

df <- tibble(a=c(NA, 1, 0), b=c(2, 0, NA))

I now want to replace all NA with zero. However, in order to distinguish between a NA-zero and an actual zero, there should be an a_is_na and b_is_na column.

I know that this can easily done with mutate like mutate(a_is_na = is.na(a)). However, I have about 20 columns and what to automatically create the correct column names and values. What is a clever way in R to do so?

1 Answers

Use across:

library(dplyr)

df %>% 
  mutate(across(a:b, is.na, .names = "{.col}_is_na")) %>% 
  replace(is.na(.), 0)

# A tibble: 3 × 4
      a     b a_is_na b_is_na
  <dbl> <dbl> <lgl>   <lgl>  
1     0     2 TRUE    FALSE  
2     1     0 FALSE   FALSE  
3     0     0 FALSE   TRUE  
Related