Understanding attributes and lists

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

Created on 2022-08-09 by the reprex package (v2.0.1)

I'm not sure I understand why this is true. On the other hand, it does seem to work.

I think you have bailed me out. (Once again.)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.