pd441
pd441

Reputation: 2763

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

Upvotes: 0

Views: 1575

Answers (2)

Carl Boneri
Carl Boneri

Reputation: 2722

Are you wanting the result to be a list of data frames -- or 1 data frame with each of the "new[n]" columns appended? My assumption was the second...

try_me <- cbind(df, as.data.frame(lapply(2:4, function(i){
    new <-  apply(df[,c(i,i + 3,i + 6)], 1, sum, na.rm = T)
    new_new <- setNames(as.data.frame(new), sprintf('new%s', i))
    new_new
})))




> head(try_me[,10:length(try_me)], 3)
         x10        x11        x12       new2      new3      new4
1 -0.5166034 -2.3482017  1.1860505 -3.1887135 -2.556875  1.971905
2  1.6145366 -0.6343859 -0.1606501  0.5623611  1.606436  1.657789
3  0.3042580 -0.2176613  1.6796682  1.3500827 -1.022463 -1.182379

Upvotes: 1

www
www

Reputation: 39154

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
}

Upvotes: 3

Related Questions