Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When exactly does data.table preserve column names?

Tags:

r

data.table

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?

like image 511
Kodiologist Avatar asked Dec 12 '18 15:12

Kodiologist


People also ask

Is data table DT == true?

data. table(DT) is TRUE. To better description, I put parts of my original code here. So you may understand where goes wrong.

What is data table in R?

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.


Video Answer


1 Answers

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.

like image 186
eddi Avatar answered Sep 23 '22 01:09

eddi