Home > database >  How to create columns in a loop?
How to create columns in a loop?

Time:10-15

I would like to create some columns with a loop. I am not sure why it is not working. To simplify, let's just assume that I want several columns with missing values.

Below are just some codes I've tried:

varlist <- c("5000_A", "5000_B", "5000_C", "5000_D", 
             "5000_E", "5000_F", "5000_G", "5000_G")

for(i in varlist){
  df <- df %>% mutate(i = NA)
}

I have also tried:

letterseq <- c(LETTERS[1:8])
for(i in letterseq){
  df <- df %>% mutate(paste("5000", i, sep = "_"), NA)
}

Or even:

letterseq <- c(LETTERS[1:8])
for(i in letterseq){
  df <- df %>% assign(paste("5000", i, sep = "_"), NA)
}

All are giving me different errors. I would like to get by the end of the code 8 different columns called 5000_A, 5000_B, 5000_C, 5000_D, 5000_E, 5000_F, 5000_G, 5000_H.

CodePudding user response:

varlist <- c("5000_A", "5000_B", "5000_C", "5000_D", 
             "5000_E", "5000_F", "5000_G", "5000_G")

for(i in varlist){
  df[[i]] <- NA
}

CodePudding user response:

Here is a solution using the package data.table.

dt[, varlist[1:length(varlist)]:=NA]

For example...

library(data.table)

varlist <- c("5000_A", "5000_B", "5000_C", "5000_D", 
             "5000_E", "5000_F", "5000_G", "5000_H")

dt <- data.table("A" = c(1,2,3), B = c("a", "b", "c"))

dt[, varlist[1:length(varlist)]:=NA]

> dt
   A B 5000_A 5000_B 5000_C 5000_D 5000_E 5000_F 5000_G 5000_H
1: 1 a     NA     NA     NA     NA     NA     NA     NA     NA
2: 2 b     NA     NA     NA     NA     NA     NA     NA     NA
3: 3 c     NA     NA     NA     NA     NA     NA     NA     NA
  • Related