I am trying to use r data.table to perform the following calculation:
I have a table with categorical columns and one numerical column, such as
cat1 cat2 cat3 target
0 x xy xxx 1
1 x xx xxx 1
2 x xx yyy 0
3 y yx yyy 1
4 y yy yyy 0
5 y yy yyy 1
I would like to calculate a table of the same shape, where, for each categorical variable, the level has been changed to the mean of the target column for that level.
i.e. the result for the above data.table would be
cat1 cat2 cat3 target
0 0.66 1 1 1
1 0.66 0.5 1 1
2 0.66 0.5 0.5 0
3 0.66 1 0.5 1
4 0.66 0.5 0.5 0
5 0.66 0.5 0.5 1
Please, no solutions using regular r dataframes, only data.table, as I am doing this as an exercise to get better in using data.tables, thanks!!
dt[,mean(target),by=catx], and merging the result back to this data.table for each variable. Just wondering if data.table wizards out there have a more elegant solution. - SolidSnake