create multiple new columns in a dataframe from a vector

I have the situation:

vector_a <- c("a", "b", "c", "x", "y", "z")
vector_b <- c("a", "b", "c")

vector_missing_columns <- vector_a %>% setdiff(vector_b)

df_test <- data_frame("a" = 1, "b" = 2, "c" = 3)

I am looking for a way to create new columns in dataframe "df_test" from the vector "vector_missing_columns".

What I have tried unsuccessfully:
df_new <- df_test %>% mutate_at(vector_missing_columns, funs(NA))

This can be one approach:

library(magrittr)
vector_a <- c("a", "b", "c", "x", "y", "z")
vector_b <- c("a", "b", "c")

vector_missing_columns <- vector_a %>% 
  setdiff(vector_b) %>%
  tibble::enframe() %>%
  dplyr::mutate(name = NA) %>%
  tidyr::spread(key = value, value = name)

df_test <- tibble::data_frame("a" = 1, "b" = 2, "c" = 3) %>%
  dplyr::bind_cols(vector_missing_columns)

df_test
#> # A tibble: 1 x 6
#>       a     b     c x     y     z    
#>   <dbl> <dbl> <dbl> <lgl> <lgl> <lgl>
#> 1     1     2     3 NA    NA    NA

Created on 2018-11-15 by the reprex package (v0.2.1)

2 Likes

Works fine! Thank You! Much appreciated.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.