-1

I have a numeric vector, say new_cols <- c(10, 20, 30), and I want to add new empty columns to an existing tibble where the column names are take from the above list. Even though the native data.frame doesn't support numeric columns, I can get away with it using tibble.

The answer given in this question provides df[new_cols] as the solution but it wouldn't work with numeric vector.

Currently I'm looping through the vector and creating new columns using mutate, there must be a more elegant way to do this using tidyverse.

msunij
  • 309
  • 2
  • 8

1 Answers1

3

The solution presented in the comment is the best. But you can also use this unusual, ugly, verbose solution:

library(purrr)

df %>%
  bind_cols(new_cols %>%
              map_dfc(~ df %>% 
                        transmute("{.x}" := NA)))

# A tibble: 3 x 5
      a     b x     y     z    
  <int> <int> <lgl> <lgl> <lgl>
1     1     4 NA    NA    NA   
2     2     5 NA    NA    NA   
3     3     6 NA    NA    NA   
Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41