Home > Back-end >  In R, how to give a vector of strings to make into empty columns?
In R, how to give a vector of strings to make into empty columns?

Time:01-27

If I have a vector of strings, how can I easily make them into column headers appended onto a dataframe? I know I could use cbind one-by-one, but is there a way to do it in one pass?

library(dplyr)
my_new_cols <- c("n_a", "n_b", "n_c")

current_data <- tibble(id = c(1:4),
                       score = c(10, 20, 30, 40))

desired_output <- tibble(id = c(1:4),
                       score = c(10, 20, 30, 40),
                       n_a = NA,
                       n_b = NA,
                       n_c = NA)
~~~~~

CodePudding user response:

One simple way:

current_data[my_new_cols] <- NA

This syntax refers to the three new columns you want to add, creating them in the process, and assigning NA for all column values.

CodePudding user response:

Here is a data.table option:

my_new_cols <- c("n_a", "n_b", "n_c")

library(data.table)
setDT(current_data)[,(my_new_cols) := NA]
current_data
#>    id score n_a n_b n_c
#> 1:  1    10  NA  NA  NA
#> 2:  2    20  NA  NA  NA
#> 3:  3    30  NA  NA  NA
#> 4:  4    40  NA  NA  NA

Created on 2023-01-26 with reprex v2.0.2

CodePudding user response:

We can also use the tidyverse:

library(dplyr)
library(purrr)

current_data %>%
    bind_cols(map_dfc(my_new_cols, ~NA) %>%
                  set_names(my_new_cols)
             )

# A tibble: 4 × 5
     id score n_a   n_b   n_c  
  <int> <dbl> <lgl> <lgl> <lgl>
1     1    10 NA    NA    NA   
2     2    20 NA    NA    NA   
3     3    30 NA    NA    NA   
4     4    40 NA    NA    NA   
  •  Tags:  
  • r
  • Related