Updated R code with library(data.table)