Hi folks, I find I don't understand something about lists and attributes. Here's a little code snippet followed by an explanation.
> rm(list=ls())
> el <- list()
> a <- list(a="a")
> attr(a,"b") <- "foo"
> attributes(a)
$names
[1] "a"
$b
[1] "foo"
> el[1] <- a
> el[1]
[[1]]
[1] "a"
> attributes(el)
NULL
> attributes(el[1])
NULL
> attributes(el[[1]])
NULL
I've made an empty list named el and another list called a. I assigned a the attribute b with value "foo", which seems to work fine.
I then assigned the first element of el to be the list a. This seems to work fine.
But when I try to access the elements of el and recover the attribute it doesn't work.
Clearly, there's something I don't understand. (I hope it's something dumb rather than something deep.)
This isn't really an explanantion; it is more of an observation. If you assign a to el using a double bracket, then the object stored in el is a list and it keeps its attribute. If you do the assignment using a single bracket, the object stored in el is a vector and it loses its attribute. If I think about the difference between subsetting lists with single and double brackets, that makes sense, but I'm struggling to articulate it without waving my hands.
el <- list()
a <- list(a="a")
attr(a,"b") <- "foo"
attributes(a)
#> $names
#> [1] "a"
#>
#> $b
#> [1] "foo"
el[[1]] <- a
el[1]
#> [[1]]
#> [[1]]$a
#> [1] "a"
#>
#> attr(,"b")
#> [1] "foo"
el[[1]]
#> $a
#> [1] "a"
#>
#> attr(,"b")
#> [1] "foo"
class(el[[1]])
#> [1] "list"
el[2] <- a
el[2]
#> [[1]]
#> [1] "a"
el[[2]]
#> [1] "a"
class(el[[2]])
#> [1] "character"
attributes(el)
#> NULL
attributes(el[[1]])
#> $names
#> [1] "a"
#>
#> $b
#> [1] "foo"
attributes(el[[2]])
#> NULL