How to change type of target column when doing := by group in a data.table in R?

We can convert the class of ‘x’ column to ‘numeric’ before assigning the ‘mean(y)’ to ‘x’ as the class of ‘x’ is ‘integer’. This may be useful if we are replacing ‘x’ with the mean of any other numeric variable (including ‘x’).

db[, x:= as.numeric(x)][, x:= mean(y), by=id][]

Or assign to a new column, and change the column name afterwards

setnames(db[, x1:= mean(y),by=id][,x:=NULL],'x1', 'x')

Or we can assign ‘x’ to ‘NULL’ and then create ‘x’ as the mean of ‘y’ ( @David Arenburg’s suggestion)

db[, x:=NULL][, x:= mean(y), by= id][]

Leave a Comment