Add empty columns programmatically

Hi
I want to add columns based on a list. Something like

df <- tibble(x = 1:3, y = 3:1)

l <- dim(df)[1]

a <- c("a", "b")

for (i in a) {
    df <- add_column(df, i = rep(NA, l))
}

This is not working, Any ideas how to do this?
Thanks
Renger

I perceive a problem which would depend on whether you know the column type you want to have or not... but the technical way to do what you are trying requires library(rlang)

df <- tibble(x = 1:3, y = 3:1)

l <- dim(df)[1]

a <- c("a", "b")

for (i in a) {
  df <- add_column(df, !!sym(i) := rep(NA, l))
}

sym to treat character of 'a' (or 'b') as a symbol , bangbang !! to force an evaluation, and := to allow the for left hand size to be determined programatically.

3 Likes

Sometimes the non-tidyverse method seems easier to me.

library(tibble)
df <- tibble(x = 1:3, y = 3:1)

a <- c("a", "b")

for (i in a) {
  df[i] <- NA
}
df
#> # A tibble: 3 x 4
#>       x     y a     b    
#>   <int> <int> <lgl> <lgl>
#> 1     1     3 NA    NA   
#> 2     2     2 NA    NA   
#> 3     3     1 NA    NA

Created on 2020-08-17 by the reprex package (v0.3.0)

Edit:
Even this works.

library(tibble)
df <- tibble(x = 1:3, y = 3:1)

a <- c("a", "b")

df[a] <- NA
4 Likes

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.