[Rd] names<- bug or feature?

Duncan Murdoch murdoch at stats.uwo.ca
Fri May 23 20:48:52 CEST 2008


On 5/23/2008 2:22 PM, Patrick Burns wrote:
> The two statements below with 'names' are conceptually
> the same.  The second performs the desired operation
> while the first does not.
> 
>  > xx <- list(A=c(a=1, b=2))
>  > names(xx$A[1]) <- "changed"
>  > xx
> $A
> a b
> 1 2
> 
>  > names(xx$A)[1] <- "changed"
>  > xx
> $A
> changed       b
>       1       2
> 
> This is observed in 2.4.0 on Linux as well as 2.7.0 and
> 2.8.0  on Windows XP.

Those aren't the same.  The first one says to extract the first element 
of xx$A and set its names.  The second says to set the first name of xx$A.

Remember that names(x) <- y is the same as

*tmp* <- x
x <- `names<-`(*tmp*, y)

which in your first case expands to

*tmp* <- xx$A[1]
xx$A[1] <- `names<-`(*tmp*, "changed")

But assigning a named number to a numeric vector has no effect on the 
names.  It would be like

xx <- c(a=1, b=2)
xx[1] <- c(d=1)

which has no effect on xx.

Duncan Murdoch



More information about the R-devel mailing list