Search code examples
rdplyr

How to create sequential columns with one function in R


I have a dataset that needs to be modified to include 30 additional columns (up to field7_30), none of which will contain data. Is there way to write this without using 30 separate mutate functions?

df<- as.data.frame(ID = c(1:5),field7_01 = c(0,0,1,1,3))
df<-df%>%
mutate(field7_02 = '', field7_03='')

Solution

  • Here is one tidyverse possibility:

    library(dplyr)
    library(stringr)
    library(purrr)
    
    df |>
      mutate(!!!map(set_names(str_c("field7_", str_pad(2:30, 2, "left", "0"))), ~ ''))
    

    As you can see this is not nearly as succinct as the base R solution.