[R] learning R

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Wed Feb 25 09:42:18 CET 2009


David Winsemius wrote:
>
> On Feb 24, 2009, at 11:36 PM, Fuchs Ira wrote:
>
>> I was wondering why the following doesn't work:
>>
>> > a=c(1,2)
>> > names(a)=c("one","two")
>> > a
>> one two
>>  1   2
>> >
>> > names(a[2])
>> [1] "two"
>> >
>> > names(a[2])="too"
>> > names(a)
>> [1] "one" "two"
>> > a
>> one two
>>  1   2
>>
>> I must not be understanding some basic concept here.
>> Why doesn't the 2nd name change to "too"?
>
> I cannot tell you why, perhaps you are not actually working with the
> names of a, but I can show you that:
>
> > names(a)[2] <- "too"
> > a[2]
> too
>   2
> > a
> one too
>   1   2
>
> And this is seen as well in the help page examples. The help page also
> says the following, which I cannot understand:
>
> It is possible to update just part of the names attribute via the
> general rules: see the examples. This works because the expression
> there is evaluated as z <- "names<-"(z, "[<-"(names(z), 3, "c2")).
>

the following:

    names(a[2]) = 'foo'

has (partially) a functional flavour, in that you assign to the names of
a *copy* of a part of a, while

    names(a)[2] = 'foo'

does not have the flavour, in that you assign to the names of a;  it
seems, according to the man page you quote, to be equivalent to:

    a = 'names<-'(a, '[<-.'(names(a), 2, 'foo'))

which proceeds as follows:

    tmp1 = names(a)
    # get a copy of the names of a, no effect on a

    tmp2 = '[<-'(tmp1, 2, 'foo')
    # get a copy of tmp1 with the second element replaced with 'foo'
    # no effect on either a or tmp1

    tmp3 = 'names<-'(a, tmp2)
    # get a copy of a with its names replaced with tmp2
    # no effect on either a, tmp1, or tmp2

    a = tmp3
    # backassign the result to a

vQ




More information about the R-help mailing list