how to add a column to a dataframe in r for loop code example

Example: add columns to dataframe r loop

for(i in 1:3) {                                   # Head of for-loop
  new <- rep(i, nrow(data))                       # Create new column
  data[ , ncol(data) + 1] <- new                  # Append new column
  colnames(data)[ncol(data)] <- paste0("new", i)  # Rename column name
}

Tags:

Misc Example