fixed by reference issues

x is passed by ref into this function so y must originally be created using as.data.table to avoid x being converted to a DT outside the function.
y is can be converted back to data frame using setDF. This is faster than as.data.frame because it is converted in place rather than being copied.