Search code examples
rdataframeloopsr-colnames

Create names for new columns within a loop


I am adding together every third column and putting the result in a new column, I have to do this across a data frame with over 300 columns. I can make the loop to perform the addition but I'm having trouble with naming the new columns. Here's an example of what I want I have tried so var:

x1 <- rnorm(100)
x2 <- rnorm(100)
x3 <- rnorm(100)
x4 <- rnorm(100)
x5 <- rnorm(100)
x6 <- rnorm(100)
x7 <- rnorm(100)
x8 <- rnorm(100)
x9 <- rnorm(100)
x10 <- rnorm(100)
x11 <- rnorm(100)
x12 <- rnorm(100)
df <- data.frame(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10, x11,x12)

for (i in 2:4){
  new <-  apply(df[,c(i,i+3,i+6)],1,sum,na.rm=T)
  df <- cbind(df, new[i-1])
}

I would like the names of the new columns to appear as "new1", "new2" and "new3" however, with my code they are all named "new[i]. Please not that I am sure that there are other and perhaps better ways to create this columns without the use of a loop but I am specifically interested in finding out what is wrong with my loop and maintaining the use of it.Thanks


Solution

  • Replace the cbind to the following, and then you will be able to assign new column names.

    for (i in 2:4){
      new <-  apply(df[,c(i,i+3,i+6)],1,sum,na.rm=T)
      df[paste0("new", i-1)] <- new
    }