If I have a data frame where I am adding columns, and I would like one column to sum them up. I will not know the names of the columns ahead of time, so I guess I would need some kind of function that would count the number of columns and then sum them up.
If my data is like this:
w=1:10
x=11:20
z=data.frame(w,x)
I would like the total for z$w and z$x. But then if I were to add z$y, I would like to have that incorporated into the sum as well.
You should consider not adding a column for the sum, and just call
rowSums(z)whenever you need it. That removes the hassle of having to update the column whenever you modify your data.frame.Now if that’s really what you want, here is a little function that will update the sum and always keep it as the last column. You’ll have to run it every time you make a change to your data.frame: