I have a data.table that looks like this:
# Load library
library(data.table)
# Set RNG seed
set.seed(-1)
# Create data table
dt <- data.table(year = 2000:2019,
value = runif(20))
# Peek
dt
#> year value
#> 1: 2000 0.48666718
#> 2: 2001 0.19136526
#> 3: 2002 0.99327188
#> 4: 2003 0.14670268
#> 5: 2004 0.24158948
#> 6: 2005 0.53710122
#> 7: 2006 0.35821235
#> 8: 2007 0.87191898
#> 9: 2008 0.39259106
#> 10: 2009 0.21656725
#> 11: 2010 0.79346199
#> 12: 2011 0.26007283
#> 13: 2012 0.26831560
#> 14: 2013 0.53564863
#> 15: 2014 0.29142160
#> 16: 2015 0.94810504
#> 17: 2016 0.06352872
#> 18: 2017 0.09133961
#> 19: 2018 0.31097680
#> 20: 2019 0.76861987
I'd like to calculate standard scores for value
and then drop the value
variable. To do this, I use chaining: in my first set of square brackets I calculate my standard score (ss
), then in my second set of square brackets I select the columns year
and ss
thus dropping value
.
# Calculate standard score and drop 'value' column
dt[, ss := as.vector(scale(value))][, .(year, ss)]
#> year ss
#> 1: 2000 0.1656755
#> 2: 2001 -0.8473906
#> 3: 2002 1.9036392
#> 4: 2003 -1.0006105
#> 5: 2004 -0.6750908
#> 6: 2005 0.3386950
#> 7: 2006 -0.2750031
#> 8: 2007 1.4873246
#> 9: 2008 -0.1570631
#> 10: 2009 -0.7609324
#> 11: 2010 1.2181692
#> 12: 2011 -0.6116816
#> 13: 2012 -0.5834039
#> 14: 2013 0.3337118
#> 15: 2014 -0.5041362
#> 16: 2015 1.7486893
#> 17: 2016 -1.2859481
#> 18: 2017 -1.1905397
#> 19: 2018 -0.4370499
#> 20: 2019 1.1329455
Created on 2019-08-07 by the reprex package (v0.3.0)
This is my desired result.
My question: do I have to use a chain in this situation or is there a way to update (i.e., calculate ss
) and select the columns I want within a single set of []
?
dt[, ss := as.vector(scale(value))][, value := NULL]
- Sotosdt[, .(year, ss = scale(value))]
? - Roland