Creating Columns Based on a Vector

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)]

Using dplyr

for (col in missing_cols) { iris_missing <- iris_missing %>% mutate(!!col := 0) }

Using base R

for (col in missing_cols) { iris_missing[[col]] <- 0 }

head(iris_missing)

> Petal.Width Species Sepal.Length Sepal.Width Petal.Length

> 1 0.2 setosa 0 0 0

> 2 0.2 setosa 0 0 0

> 3 0.2 setosa 0 0 0

> 4 0.2 setosa 0 0 0

> 5 0.2 setosa 0 0 0

> 6 0.4 setosa 0 0 0

```

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)

>

> Attaching package: 'dplyr'

> The following objects are masked from 'package:stats':

>

> filter, lag

> The following objects are masked from 'package:base':

>

> intersect, setdiff, setequal, union

library(purrr)

iris_missing <- iris[c(4:5)]

missing_cols <- names(iris)[!names(iris) %in% names(iris_missing)]

Using dplyr/purrr

iris_missing <- iris_missing %>% bind_cols( map_dfc(missing_cols, ~ transmute(iris_missing, !!.x := 0)) )

head(iris_missing)

> Petal.Width Species Sepal.Length Sepal.Width Petal.Length

> 1 0.2 setosa 0 0 0

> 2 0.2 setosa 0 0 0

> 3 0.2 setosa 0 0 0

> 4 0.2 setosa 0 0 0

> 5 0.2 setosa 0 0 0

> 6 0.4 setosa 0 0 0

```

/r/rstats Thread