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!