names<- bug, and incompatibility with c() (PR#2358)
This is S-compatible, though, and it I think it is quite legitimately an error. I will fix it in R-devel, but I am little concerned that advanced users may be surprised (but they probably would never do this).
there is inconsistent behaviour depending on whether the element being named
is the last one:
test> mm <- 1:3
test> names( mm)[1] <- 'y'
Error in "names<-.default"(*tmp*, value = "y") :
names attribute must be the same length as the vector
test> names( mm)[2] <- 'y'
Error in "names<-.default"(*tmp*, value = "y") :
names attribute must be the same length as the vector
test> names( mm)[3] <- 'y'
test> mm
<NA> <NA> y
1 2 3
As long as the last element of mm gets mentioned, R will allow the
operation, filling in any blanks with NA-strings. But if the last element of
mm isn't specified somewhere in the vector of things-to-be-named, R won't
allow the operation.
If mm already has names, there's no problem.
The usage above is sometimes valuable, and it should be easy to fix it, by
supplying default names in all other positions. But there is also some
inconsistency with the use of "c": should default names be NA-strings, or
empty strings?
They should now be NA-strings.
test> mm <- 1:2 test> names( mm)[2] <- 'y' test> mm <NA> y 1 2 test> mm <- c( mm, 3) test> mm NA y 1 2 3 test> names( mm)[1] [1] "NA" test> Note that "c" has supplied an empty string for the unspecified name, and has also taken the liberty of changing the special NA-string into a "NA" (i.e. a 2-character string, first letter N, second letter A)!
That's a bug.
An easy way to achieve consistency, would be to make unsupplied names should always default to an empty string, rather than a special NA-string.
But what's the point of having a special string then?
Brian D. Ripley, ripley@stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272860 (secr) Oxford OX1 3TG, UK Fax: +44 1865 272595