# [R] "[[" gotcha

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Jan 16 12:11:36 CET 2007

```On Tue, 16 Jan 2007, Robin Hankin wrote:

> The following gotcha caught me off-guard just now.

Checking the relevant help page is always a good idea (and that is why the
posting guide asks that you do so before posting).

> I have two matrices, a and b:
>
>
> a <- matrix(1,3,3)
> b <- matrix(1,1,1)
>
> (note that both "a" and "b" are matrices).
>
> I want them in a list:
>
> > B <- NULL

So why did you not create a list, e.g. by list() or vector("list", 2)?

> > B[] <- a
> > B[] <- b
> > B
> []
>      [,1] [,2] [,3]
> [1,]    1    1    1
> [2,]    1    1    1
> [3,]    1    1    1
>
> []
>      [,1]
> [1,]    1
>
> >
>
> This is fine.
>
> But swapping "a" and "b" over does not behave as desired:
>
>
> > B <- NULL
> > B[] <- b
> > B[] <- a
> Error in B[] <- a : more elements supplied than there are to replace
> >
>
>
>
> The error is given because after B[] <- a,   the variable B is
> just a scalar and
> not a matrix (why is this?)

You said wanted a list, and got a numeric vector (R has no scalars).
In your first example you got a length-one list, not a matrix.

The type-promotion rules for [<- and [[<- are complex, and you should not
rely on knowing what they currently are (they do change from time to
time).  But this one is right there on the help page (?"[["):

When '\$<-' is applied to a 'NULL' 'x', it first coerces 'x' to
'list()'.  This is what also happens with '[[<-' if the
replacement value 'value' is of length greater than one: if
'value' has length 1 or 0, 'x' is first coerced to a zero-length
vector of the type of 'value'.

> What's the bulletproof method for assigning matrices to a list (whose
> length is not known at runtime)?