Reputation: 1363
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?
Upvotes: 1
Views: 184
Reputation: 887901
Another option is
Reduce(`+`, df[-3])
#[1] 7 7 7 7 7
Or a variant of @PierreLafortune
df$a + df$b + df$d
#[1] 7 7 7 7 7
Upvotes: 1
Reputation: 33613
Another solution using data.table
:
require(data.table) # Load package
dt <- data.table(df) # Convert to data.table
dt[, a + b + d] # Sum columns
[1] 7 7 7 7 7
Upvotes: 1
Reputation: 628
Or within a data.table
:
dt[, sum := rowSums(.SD), .SDcols = c(1, 2, 4)]
dt[, sum := rowSums(.SD), .SDcols = c('a', 'b', 'd')]
Upvotes: 2
Reputation: 1291
You can use the rowSums function and refer to columns by setting a vector of column numbers in df[, ]
.
rowSums(df[, c(1,2,4)]
[1] 7 7 7 7 7
Upvotes: 1