[Rd] Inconsistency when naming a vector

peter dalgaard pdalgd at gmail.com
Mon Apr 27 15:33:35 CEST 2015


> On 27 Apr 2015, at 13:48 , Hadley Wickham <h.wickham at gmail.com> wrote:
> 
> Sometimes the absence of a name is maked by an NA:
> 
> x <- 1:2
> names(x)[[1]] <- "a"
> names(x)
> # [1] "a" NA
> 
> Whereas other times its
> 
> y <- c(a = 1, 2)
> names(y)
> # [1] "a" ""
> 
> Is this deliberate? The help for names() is a bit murky, but an
> example shows the NA behaviour.

I think it is 

(a) impossible to change
(b) at least somewhat coherent

The situation is partially due to the fact that character-NA is a relative latecomer to the language. In the beginning, there was no real distinction between NA and "NA", causing issues when abbreviating Noradrenaline, North America, Nelson Anderson, etc. At some point, it was decided to fix things up, as far as possible in a backawards compatible way. Some common idioms were retained but others were changed to comply with the rules for other vector types.

We have the empty string convention on (AFAICT) all constructor usages:

c(a=1, 3) 
list(a=1, 3)
cbind(a=1, 3)

and also in the lists implied by argument matching

> f <- function(...) names(match.call(expand.dots=TRUE))
> f(a=1,3)
[1] ""  "a" "" 

In contrast, assignment forms have the NA convention. This is consistent with the general rules for complex assignment. E.g. we have

> a <- "a"
> a[[5]] <- "b"
> a
[1] "a" NA  NA  NA  "b"

and even

> a <- NULL
> a[[5]] <- "a"
> a
[1] NA  NA  NA  NA  "a"

also, we have

> l <- list(1,2,3)
> names(l) <- c("a","b")
> l
$a
[1] 1

$b
[1] 2

$<NA>
[1] 3

and we do want to obey general rules like

names(l)[[2]] <- "a" 

being (nearly) equivalent to

`*tmp*`<- names(l)
`*tmp*`[[2]] <- "a"
names(l) <- `*tmp*`


- pd

> 
> Hadley
> 
> -- 
> http://had.co.nz/
> 
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-devel mailing list