The difference between my question and existing questions is that I want to create new columns with mutate
that do not depend on existing columns.
Some dummy data:
library(dplyr)
dat <- tibble(
a = 1:5,
b = LETTERS[1:5]
)
I know I can create new columns one-by-one like so
dat <- dat %>%
mutate(foo = NA, bar = NA, bar2 = NA)
And I can modify columns more conveniently using across
, e.g. :
new_vars <- c("foo", "bar", "bar2")
dat <- dat %>%
mutate(across(all_of(new_vars), ~ replace(., is.na(.), 0)))
But how do I create new columns without referencing existing columns in a similar manner? E.g. adding new columns filled with NA
:
tibble(
a = 1:5,
b = LETTERS[1:5]
) %>%
# mutate(across(all_of(new_vars), ~ function(.x) NA)) # Error
mutate(across(all_of(new_vars), NA)) # Error
Open to any tidyverse
alternatives.