From Waclaw.Marcin.Kusnierczyk at idi.ntnu.no  Mon Mar 23 09:52:19 2009
From: Waclaw.Marcin.Kusnierczyk at idi.ntnu.no (Wacek Kusnierczyk)
Date: Mon, 23 Mar 2009 09:52:19 +0100
Subject: [Rd] incoherent treatment of NULL
Message-ID: <49C74DC3.3090700@idi.ntnu.no>

somewhat related to a previous discussion [1] on how 'names<-' would
sometimes modify its argument in place, and sometimes produce a modified
copy without changing the original, here's another example of how it
becomes visible to the user when r makes or doesn't make a copy of an
object:

    x = NULL
    dput(x)
    # NULL
    class(x) = 'integer'
    # error: invalid (NULL) left side of assignment

    x = c()
    dput(x)
    # NULL
    class(x) = 'integer'
    dput(x)
    # integer(0)

in both cases, x ends up with the value NULL (the no-value object).  in
both cases, dput explains that x is NULL.  in both cases, an attempt is
made to make x be an empty integer vector.  the first fails, because it
tries to modify NULL itself, the latter apparently does not and succeeds.

however, the following has a different pattern:

    x = NULL
    dput(x)
    # NULL
    names(x) = character(0)
    # error: attempt to set an attribute on NULL

    x = c()
    dput(x)
    # NULL
    names(x) = character(0)
    # error: attempt to set an attribute on NULL

and also:

    x = c()
    class(x) = 'integer'
    # fine
    class(x) = 'foo'
    # error: attempt to set an attribute on NULL

how come?  the behaviour can obviously be explained by looking at the
source code (hardly surprisingly, because it is as it is because the
source is as it is), and referring to the NAMED property (i.e., the
sxpinfo.named field of a SEXPREC struct).  but can the *design* be
justified?  can the apparent incoherences visible above the interface be
defended? 

why should the first example above be unable to produce an empty integer
vector? 

why is it possible to set a class attribute, but not a names attribute,
on c()? 

why is it possible to set the class attribute in c() to 'integer', but
not to 'foo'? 

why are there different error messages for apparently the same problem?


vQ


[1] search the rd archives for 'surprising behaviour of names<-'



[Rd] incoherent treatment of NULL
Wacek Kusnierczyk