0

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

aynber
  • 22,380
  • 8
  • 50
  • 63
pd441
  • 2,644
  • 9
  • 30
  • 41
  • 1
    FYI, a more R-ish, vectorized way to do this would be `cbind(df, setNames(data.frame(rowSums(df[c(T, F, F)]), rowSums(df[c(F, T, F)]), rowSums(df[c(F, F, T)])), paste0('new', seq(ncol(df) / 4))))` – Sotos Aug 01 '17 at 14:12

2 Answers2

3

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
}
www
  • 38,575
  • 12
  • 48
  • 84
  • 1
    Great thanks! i also found that adding `names(df)[names(df) == "new"] <- paste("new",i-1)` will solve it – pd441 Aug 01 '17 at 14:13
1

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
Carl Boneri
  • 2,632
  • 1
  • 13
  • 15