How to do vector sum (i.e. row sum, element by element) in dplyr
.
Data to play with:
> dt <- ggplot2::diamonds[1:3,5:10]
depth table price x y z
1: 61.5 55 326 3.95 3.98 2.43
2: 59.8 61 326 3.89 3.84 2.31
3: 56.9 65 327 4.05 4.07 2.31
I'd like to add a column Total
to the dt
which will be equal to element by element sum of columns" cols <- 3:5
NB1: I know how to do it in data.table: dt [ , Total:= rowSums(.SD), .SDcols=cols]
NB2: In dplyr, we can do: dt %>% mutate(Total=x+y+z)
. But how to do it in column-name agnostic waycols=3:5
(or for cols=3:5000
) ?
PS. This question was originally asked here: How to do vector/row sum (element by element) in data.table and dplyr?, but was closed by someone as Duplicate before it was answered.