From Waclaw.Marcin.Kusnierczyk at idi.ntnu.no  Tue Mar 10 15:44:01 2009
From: Waclaw.Marcin.Kusnierczyk at idi.ntnu.no (Wacek Kusnierczyk)
Date: Tue, 10 Mar 2009 15:44:01 +0100
Subject: [Rd] surprising behaviour of names<-
Message-ID: <49B67CB1.8060005@idi.ntnu.no>

playing with 'names<-', i observed the following:
  
    x = 1
    names(x)
    # NULL
    'names<-'(x, 'foo')
    # c(foo=1)
    names(x)
    # NULL

where 'names<-' has a functional flavour (does not change x), but:

    x = 1:2
    names(x)
    # NULL
    'names<-'(x, 'foo')
    # c(foo=1, 2)
    names(x)
    # "foo" NA
  
where 'names<-' seems to perform a side effect on x (destructively
modifies x).  furthermore:

    x = c(foo=1)
    names(x)
    # "foo"
    'names<-'(x, NULL)
    names(x)
    # NULL
    'names<-'(x, 'bar')
    names(x)
    # "bar" !!!

    x = c(foo=1)
    names(x)
    # "foo"
    'names<-'(x, 'bar')
    names(x)
    # "bar" !!!

where 'names<-' is not only able to destructively remove names from x,
but also destructively add or modify them (quite unlike in the first
example above).

analogous code but using 'dimnames<-' on a matrix performs a side effect
on the matrix even if it initially does not have dimnames:

    x = matrix(1,1,1)
    dimnames(x)
    # NULL
    'dimnames<-'(x, list('foo', 'bar'))
    dimnames(x)
    # list("foo", "bar")

this is incoherent with the first example above, in that in both cases
the structure initially has no names or dimnames attribute, but the end
result is different in the two examples.

is there something i misunderstand here?


there is another, minor issue with names:

    'names<-'(1, c('foo', 'bar'))
    # error: 'names' attribute [2] must be the same length as the vector [1]

    'names<-'(1:2, 'foo')
    # no error

since ?names says that "If 'value' is shorter than 'x', it is extended
by character 'NA's to the length of 'x'" (where x is the vector and
value is the names vector), the error message above should say that the
names attribute must be *at most*, not *exactly*, of the length of the
vector.

regards,
vQ



[Rd] surprising behaviour of names<-
Wacek Kusnierczyk