[R] "[[" gotcha

Petr Pikal petr.pikal at precheza.cz
Tue Jan 16 11:43:03 CET 2007


Hi

try different way of list definition, see below.

On 16 Jan 2007 at 10:10, Robin Hankin wrote:

From:           	Robin Hankin <r.hankin at noc.soton.ac.uk>
Date sent:      	Tue, 16 Jan 2007 10:10:42 +0000
To:             	RHelp help <r-help at stat.math.ethz.ch>
Subject:        	[R] "[[" gotcha

> 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<-vector("list", 2)
B[[1]]<-a
B[[1]]<-b

here is no complain.
HTH
Petr

>  > 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)?
> 
> 
> 
> 
> 
> 
> 
> 
> --
> Robin Hankin
> Uncertainty Analyst
> National Oceanography Centre, Southampton
> European Way, Southampton SO14 3ZH, UK
>   tel  023-8059-7743
> 
> ______________________________________________
> R-help at 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.

Petr Pikal
petr.pikal at precheza.cz



More information about the R-help mailing list