Let's say I have 10 columns, and I want to add an 11th column that sums columns 1-6 for each row. How can I do this? I saw this on another answer:
data$newCol <- sum(data[1:6])
But that resulted in a single number for all rows in newCol, which isn't what I'm trying to do. The only way I know how to do this is like this:
data$newCol <- data$colA + data$colB + data$colC
and so on, but this gets tedious when I'm working with more than just a few columns. Is there a shortcut, like using [1:6] somehow? I'm sure this is such a beginner question, I tried searching but didn't see an answer that made sense to me, sorry.
Thank you!
You can try apply
function
data$newCol <- apply(data[,1:6], 1, sum, na.rm=TRUE)