[Rd] Attributes of a vector element?

J C Nash pro|jcn@@h @end|ng |rom gm@||@com
Tue Feb 22 20:00:35 CET 2022


Thanks for the responses. Looks like I can make something work if I pay appropriate
attention to detail.

Duncan: Should I try to submit a bug report for the missed error message? If so, do you
have suggestions for keywords?

Best, JN


On 2022-02-22 13:52, Duncan Murdoch wrote:
> On 22/02/2022 1:45 p.m., Ivan Krylov wrote:
>> 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.
> 
> That's true for atomic vectors.  lists are also vectors, and they can accept attributes on the list as a whole or on the 
> individual elements, but it would be done using
> 
>     attr(pp[[1]], "trial")<-"first"
> 
> (as I just noticed you found below).
> 
> I suspect it's an oversight that attr(pp[1], "trial") <- "first" didn't trigger an error.  It says to assign the 
> attribute on the subvector containing just the first element, but in general such things wouldn't be inherited by the 
> full vector.
> 
>>
>>> 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.
>>
> 
> Yes, you could do
> 
>    attr(pp, "trials")[1] <- "someval"
> 
> if you already had a "trials" attribute on pp.
> 
> Duncan Murdoch



More information about the R-devel mailing list