Skip to Content

Refer to columns by number in := assignment when using data.table

As per Row wise matrix operations in R I would like to apply a row-wise function on a data.table I have. I wish to calculate, per row, the mean of a number of columns in that row. My current attempt is:

columns <- c(1,5,10,15,20) # Actually obtained via grep[,"average" := mean(columns),with=FALSE] # Or...[,average := mean(columns)]

This, unfortunately, simply returns the mean of the 'columns' vector rather than mean of the columns to which they refer. Is there a way to refer to these columns by number?

Here's the average I'm trying to achieve:

key  a b c average
A    5 5 5 5
B    1 2 3 2
C    2 4 9 5