[R] Simple syntax question (I think)
Marc Schwartz
marc_schwartz at me.com
Wed Jan 20 19:57:23 CET 2016
> 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