0

The following code

library(data.table) 
dt<-data.table(a=list(b=list(c=list(d=list(e=list("f"))))))

creates a data.table with one colum 'a' consisting of a list:

> dt
    a
1: <list>

The list of 'a' consists or a set of nested lists. However, data.table forgets about the name of the first list within 'a':

> dt$a
[[1]]
[[1]]$c
[[1]]$c$d
[[1]]$c$d$e
[[1]]$c$d$e[[1]]
[1] "f"

Why that? What happens to the list with name b? What can I do to access list b by name?

Funkwecker
  • 766
  • 13
  • 22
  • 1
    Re what can be done, similar to this question https://stackoverflow.com/q/51989631/ you can do `data.table(a_nm = names(a), a_val = a)` – Frank Aug 30 '18 at 18:32

1 Answers1

1

Data.table is a rectangular format -- in your case, you have a table with a single row and a single column. If you really want to store complex objects in data.table or data.frame cells, you might enclose them in a list:

dt<-data.table(a=list(list(b=list(c=list(d=list(e=list("f")))))))

Why is the name b lost without an extra list? I suppose this is because the first element of a is interpreted as something that goes to the first row, and there are no row names in data.table. Something similar happens when you supply a named vector:

> dt2 <- data.table(a=c(b=1,c=2,d=3))
> dt2
   a
1: 1
2: 2
3: 3

(The names of the vector elements are lost and there's no way to get them back.)

This is different with data.frame:

> data.frame(a=c(b=1,c=2,d=3))
  a
b 1
c 2
d 3
lebatsnok
  • 6,329
  • 2
  • 21
  • 22
  • Re OP's how to access by name, for this answer `dt[sapply(a, names) == "b"]` works, I think – Frank Aug 30 '18 at 18:38