Skip to content
Prev 368168 / 398500 Next

Taking the sum of only some columns of a data frame

This does the summation you want in one line:

#create example data and column selection
d = as.data.frame(matrix(rnorm(50),ncol=5))
cols = c(1,3)

#sum selected columns and put results in new row
d[nrow(d)+1,cols] = colSums(d[,cols])

However, I would agree with the sentiments that this is a bad idea; far better to have the mean values stored in a new object leaving the original data table untainted.