I have a situation where I need to add an arbitrary number of columns to a tibble. The column names that I need to add will come from a list.
If it were just one column, it's easy, I would just use add_column()
.
For example, starting with tibble, df, I can add column c like this:
library(tidyverse)
df <- tibble(a = 1:3, b = 3:1)
df <- add_column(df, c = 0)
Which yields...
# A tibble: 3 × 3
a b c
<int> <int> <dbl>
1 1 3 0
2 2 2 0
3 3 1 0
That leads me to believe that if I want to add multiple columns, for example from a list, new_cols, I could just map them onto add_column()
but for some reason, I can't.
library(tidyverse)
df <- tibble(a = 1:3, b = 3:1)
new_cols <- c('d','e','f')
map(new_cols, ~ df <- add_column(df, . = 0))
... thinking about this some more of course map() is the wrong idea-- the whole point of map is to generate a list and not side-effects.
I am sure there's an easy one-liner for this, but it escapes me right now.