[Rd] Attributes of a vector element?

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Tue Feb 22 19:45:21 CET 2022


On Tue, 22 Feb 2022 13:29:15 -0500
J C Nash <profjcnash using gmail.com> wrote:

> pp<-c(1,2)
> attr(pp[1], "trial")<-"first"

I don't have a solid proof for this with a link to the R Language
Definition, but my understanding of the attributes is that they belong
to the whole vector (and that elements of a vector don't usually exist
as separate entities in R). Maybe this explains why the attribute of a
temporary value is lost in this assignment.

> pl<-list(one=1, two=2)
> attr(pl[1],"trial")<- "lfirst"

However, this could be made to work, if attributes were assigned on the
list element instead of the list slice:

attr(pl[[1]],"trial")<- "lfirst"
attr(pl[[1]],"trial")
# [1] "lfirst"

Same goes for data.frame columns:

str(data.frame(x = 1:10, y = structure(1:10, attr = 'val')))
# 'data.frame':   10 obs. of  2 variables:
#  $ x: int  1 2 3 4 5 6 7 8 9 10
#  $ y: atomic  1 2 3 4 5 6 7 8 9 10
#   ..- attr(*, "attr")= chr "val"   # <-- attribute preserved

If you need to tag rows of a data frame, your best bet would likely be
to assign a vector as an attribute of the data frame itself.

-- 
Best regards,
Ivan



More information about the R-devel mailing list