Probably easiest to do a for loop here. You can use base R or dplyr.
``` library(dplyr)
iris_missing <- iris[c(4:5)]
missing_cols <- names(iris)[!names(iris) %in% names(iris_missing)]
for (col in missing_cols) { iris_missing <- iris_missing %>% mutate(!!col := 0) }
for (col in missing_cols) { iris_missing[[col]] <- 0 }
head(iris_missing)
```
across()
is meant to apply the same transformation to a selection of columns already in the data frame. In this case the columns don't exist yet.
You could also use a combination of purrr and dplyr, but it's going to come out clunkier than a for loop solution:
``` library(dplyr)
library(purrr)
iris_missing <- iris[c(4:5)]
missing_cols <- names(iris)[!names(iris) %in% names(iris_missing)]
iris_missing <- iris_missing %>% bind_cols( map_dfc(missing_cols, ~ transmute(iris_missing, !!.x := 0)) )
head(iris_missing)
```