This question seems basic but I have not been able to find an answer to it.
I want to add columns of a data.frame
together by just referring to their indeces.
Suppose I want to add columns 1,2, and 4.
df <- data.frame(
a=rep(1, 5),
b=rep(2, 5),
c=rep(3, 5),
d=rep(4, 5)
)
I know that explicitly referring to the column names I can do
> df$a + df$b + df$d
[1] 7 7 7 7 7
And referring to indeces I can do
> df[1] + df[2] + df[4]
a
1 7
2 7
3 7
4 7
5 7
However, the index option above requires me to write out the name of the data.frame
for every column I want to add.
Is there a way to add these columns together while just referring to the indeces and the data.frame
once?