0

I have a data frame such as follows:

x1 <- c(1, 2, 3, 4, 5)
x2 <- c(1, 3, 5, 7, 9)
x3 <- c(1, 2, 1, 2, 1)
df <- data.frame(x1, x2, x3)

I would like to create a new column y that is the total values of each column. This could be done like this:

df$y <- df$x1 + df$x2 + df$x3

But I need to do it in a loop. This is the best I could do:

for (i in 1:3) {
  x <- paste0("x", i)
  df$y <- sum(df[[x]][1])
}

How can I get the for loop to give the same result as the sum above? Really appreciate the help, thanks!

Marco Pastor Mayo
  • 803
  • 11
  • 25
  • 4
    Do you really need `for` loop? You can do `rowSums(df)` – Ronak Shah Nov 12 '18 at 11:58
  • Turns out that works too. I though I needed to use a for loop because the numer of columns across my data frames varied, but that could be corrected by creating a value with the number of columns with `ncol`. So all's good. – Marco Pastor Mayo Nov 12 '18 at 12:03

1 Answers1

0

Due to vectorization you can just do:

df$y <- rowSums(df)
df

  x1 x2 x3  y
1  1  1  1  3
2  2  3  2  7
3  3  5  1  9
4  4  7  2 13
5  5  9  1 15
alex_555
  • 1,092
  • 1
  • 14
  • 27