[R] Simple syntax question (I think)

Bert Gunter bgunter.4567 at gmail.com
Wed Jan 20 20:21:38 CET 2016


Thanks Marc.

Actually, I think the cognate construction for a vector (which is what
a list is also) is:

> vector("numeric",2)[2] <-  3
Error in vector("numeric", 2)[2] <- 3 :
  target of assignment expands to non-language object

but this works:

> "[<-"(vector("numeric",2),2,3)
[1] 0 3

I would have thought the 2 versions should be identical, but as you
allude, there are apparently subtleties in the parsing/evaluation that
I do not understand, so that the explicit functional form is parsed
and evaluated differently than the implicit one. The obvious message,
though, is: don't do this!

I suspect there is a reference to this somewhere in the R Language
definition  or elsewhere, and if so, I would appreciate someone
referring me to it -- RTFM certainly applies!

Cheers,
Bert

Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Wed, Jan 20, 2016 at 10:57 AM, Marc Schwartz <marc_schwartz at me.com> wrote:
>
>> On Jan 20, 2016, at 12:26 PM, Bert Gunter <bgunter.4567 at gmail.com> wrote:
>>
>> Could someone please explain to me my mal-understanding of the
>> following, which I expected to give the same results without errors.
>>
>> TIA.
>>
>> -- Bert
>>
>>> z <-  list(x=1)
>>> z[[2]] <- 3
>>> z
>> $x
>> [1] 1
>>
>> [[2]]
>> [1] 3
>>
>>> list(x = 1)[[2]] <- 3
>> Error in list(x = 1)[[2]] <- 3 :
>>  target of assignment expands to non-language object
>
>
> Bert,
>
> I will take a stab at this.
>
> In the first case, you are adding a new element to an existing list object, so works as expected:
>
> # Create a new list 'z'
> z <-  list(x = 1)
>
>> z
> $x
> [1] 1
>
>
> # Now, add a new unnamed element in the list
> z[[2]] <- 3
>
>> z
> $x
> [1] 1
>
> [[2]]
> [1] 3
>
>
> In the second case, you are attempting to subset a list that does not yet exist and assign a value to an element of a non-existent object:
>
>> list(x = 1)[[2]]
> Error in list(x = 1)[[2]] : subscript out of bounds
>
>> list(x = 1)[[2]] <- 3
> Error in list(x = 1)[[2]] <- 3 :
>   target of assignment expands to non-language object
>
>
> If this was to work, the parser would have to evaluate the command in a left to right fashion, first creating the list with an element 'x' and then adding the new element to it as a second step, much as you did explicitly in the first approach.
>
> You get somewhat similar behavior with a vector, albeit the error is perhaps a bit more clear:
>
>> Vec
> Error: object 'Vec' not found
>
>> Vec[2] <- 3
> Error in Vec[2] <- 3 : object 'Vec' not found
>
> Vec <- 1
>
>> Vec
> [1] 1
>
> Vec[2] <- 2
>
>> Vec
> [1] 1 2
>
>
> Regards,
>
> Marc
>



More information about the R-help mailing list