Let’s say I have a vector where I’ve set a few attributes:
vec <- sample(50:100,1000, replace=TRUE)
attr(vec, "someattr") <- "Hello World"
When I subset the vector, the attributes are dropped. For example:
tmp.vec <- vec[which(vec > 80)]
attributes(tmp.vec) # Now NULL
Is there a way to, subset and persist attributes without having to save them to another temporary object?
Bonus: Where would one find documentation of this behaviour?
I would write a method for
[orsubset()(depending on how you are subsetting) and arrange for that to preserve the attributes. That would need a"class"attribute also adding to your vector so that dispatch occurs.At this point, subsetting removes attributes:
If we add a method
[.foowe can preserve the attributes:Now the desired behaviour is preserved
And the answer to the bonus question:
From
?"["in the details section:Subsetting (except by an empty index) will drop all attributes except names, dim and dimnames.