I assume this is because you wrap .SD
in list
(.()
). The list(.SD)
generates a list
containing .SD
, instead of only the .SD
. This then messes with the naming.
Check str
of .SD
wrapped in list
:
dt[, str(.(.SD)), .SDcol = my_vars]
# List of 1
# $ :Classes ‘data.table’ and 'data.frame': 5 obs. of 2 variables:
# ..$ cyl: num [1:5] 6 6 4 6 8
# ..$ vs : num [1:5] 0 0 1 1 0
Corresponding output has the .SD.
prefix:
dt[ , .(.SD), .SDcol = my_vars]
# .SD.cyl .SD.vs
# 1: 6 0
# 2: 6 0
# 3: 4 1
# 4: 6 1
# 5: 8 0
Check str
of .SD
only:
dt[, str(.SD), .SDcol = my_vars]
# Classes ‘data.table’ and 'data.frame': 5 obs. of 2 variables:
# $ cyl: num 6 6 4 6 8
# $ vs : num 0 0 1 1 0
Given the basic property of j
- "As long as j
returns a list, each element of the list becomes a column in the resulting data.table
" - and that .SD
already is a list
(check dt[ , is.list(.SD)]
), we can use c
to combine .SD
with other list elements, e.g. your renamed column wrapped in list
:
dt[, c(.SD, .(z = gear)), .SDcol = my_vars]
# cyl vs z
# 1: 6 0 4
# 2: 6 0 4
# 3: 4 1 4
# 4: 6 1 3
# 5: 8 0 3
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…