[Rd] Attributes of a vector element?

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Tue Feb 22 20:54:53 CET 2022


On 22/02/2022 2:00 p.m., J C Nash wrote:
> 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?

Actually I think it's not an R bug.  Maybe someone else can express an 
opinion.

A simpler example is:

   x <- 1:2
   names(x[1]) <- "a"

This is quite similar to the example in the Language Def,

   names(x)[3] <- "Three"

but with the order of calling `names<-` and `[<-` reversed, so I think

   names(x[1]) <- "a"

should be equivalent to

   `*tmp*` <- x
   x <- "[<-"(`*tmp*`, 1, value="names<-"(`*tmp*`[1], value="a"))
   rm(`*tmp*`)

Now the default "[<-" method doesn't copy names, but there's no reason 
why it couldn't for some special class, e.g.


   # This is what you saw:
   x <- 1:2
   names(x[1]) <- "a"
   x
   # [1] 1 2

   # This could work:
   class(x) <- "foo"

   `[<-.foo` <- function(x, i, value) {
     x <- unclass(x)
     x[i] <- value
     names(x)[i] <- names(value)
     class(x) <- "foo"
     x
   }

   names(x[1]) <- "a"
   x
   #   a <NA>
   #   1    2
   # attr(,"class")
   # [1] "foo"

So instead of an R bug, this is just a bug in your code, because you 
tried to do something on a class that didn't handle it the way you wanted.

Duncan



More information about the R-devel mailing list