Some J expressions preserve column names, and some don't:
library(data.table)
d = data.table(hello = 1)
d[, .(hello)]
# hello
# 1: 1
d[, c(.(hello))]
# V1
# 1: 1
d[, {.(hello)}]
# hello
# 1: 1
d[, {1; .(hello)}]
# V1
# 1: 1
d[, .(get("hello"))]
# V1
# 1: 1
d[, mget("hello")]
# hello
# 1: 1
d[, c(mget("hello"))]
# Error: value for ‘hello’ not found # WTF?
d[, {1; mget("hello")}]
# hello
# 1: 1
What's the general rule?
data. table(DT) is TRUE. To better description, I put parts of my original code here. So you may understand where goes wrong.
data.table is an R package that provides an enhanced version of data.frame s, which are the standard data structure for storing data in base R. In the Data section above, we already created a data.table using fread() . We can also create one using the data.table() function.
This really isn't very mysterious. First note that .
is a shorthand for list
in data.table
. With that in mind, this is what's happening.
Every single expression you have produces an unnamed list or vector, except for mget
which spits out a named list. This is why mget
examples have named results. In all of the other examples data.table
only deduces the name in very simple expressions, which are equivalent to list(items)
. There are a few more cases where you'd get name deduction that would involve .SD
, but generally speaking - if you didn't name it (as mget
does) and it's more complicated than list(items)
, then don't expect name deduction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With