Re: [R] "[[" gotcha

From: Joerg van den Hoff <j.van_den_hoff_at_fzd.de>
Date: Tue 16 Jan 2007 - 11:02:24 GMT

Robin Hankin wrote:
> The following gotcha caught me off-guard just now.
>
> 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
> > B[[1]] <- a
> > B[[2]] <- b
> > B
> [[1]]
> [,1] [,2] [,3]
> [1,] 1 1 1
> [2,] 1 1 1
> [3,] 1 1 1
>
> [[2]]
> [,1]
> [1,] 1
>
> >
>
> This is fine.
>
> But swapping "a" and "b" over does not behave as desired:
>
>
> > B <- NULL
> > B[[1]] <- b
> > B[[2]] <- a
> Error in B[[2]] <- a : more elements supplied than there are to replace
> >
>
>
>
> The error is given because after B[[1]] <- a, the variable B is
> just a scalar and
> not a matrix (why is this?)
>
> What's the bulletproof method for assigning matrices to a list (whose
> length is
> not known at runtime)?
>
>
not sure about "bulletproof", but:

you should tell R that B is really intended to be a list in the first place:

B <- list()

the rest then works as you intended. whether the 'simplification' of your 1x1 matrix to a scalar in your example is canonical (and desirable) behaviour seems a question for some of the experts (it's a bit reminiscent of the `drop = TRUE' vs. `drop = FALSE' problem)

joerg
>
>
>
>
>
>
> --
> Robin Hankin
> Uncertainty Analyst
> National Oceanography Centre, Southampton
> European Way, Southampton SO14 3ZH, UK
> tel 023-8059-7743
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Tue Jan 16 22:35:40 2007

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 16 Jan 2007 - 12:30:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.