Re: [R] Help with understanding [[]] [] array, list, matrix referencing

From: Thomas Lumley <tlumley_at_u.washington.edu>
Date: Tue 24 Oct 2006 - 14:21:25 GMT

On Tue, 24 Oct 2006, Joe W. Byers wrote:
> following code produces a 5 element list of 2X5 random numbers that I
> then convert to a 2X5X5 matrix.
> cov<-matrix(c(.4,-.1,-.1,.3),nrow=2,ncol=2)
> rnds<-NULL;
> for (i in 1:5){
> t1<-rnorm(5,cov)
> t2<-rnorm(5,cov)
> t3<-rbind(t1,t2)
> rnds[i]<-list(t3)
> }
>
> rnds.matrix<-array(unlist(rnds),dim=c(2,5,5));
>
> To access the matrix rnds.matrix I use rnds.matrix[x,y,z]. This I
> understand.
>
> To access the list I user [[z]][x,y]. This I do not understand. I
> found by chance this reference notation in an old mailing list that
> helped me.
>

Yes, this can be confusing. One reason that it is confusing is that the rules appear to be different (though they aren't) for vectors and lists.

The single bracket [ extracts a subvector, and the double bracket [[ extracts an element. That is, with
  a<-list(b=1,c=2,d=3)

you can extracts the first element of a,
> a[[1]]

[1] 1
or a sublist with the first two elements
> a[1:2]

$b
[1] 1

$c
[1] 2
or a sublist with just the first element
> a[1]

$b
[1] 1

The same is true for numeric or character vectors, but there an element and a subvector of length one are the same, so the distinction between [[ and [ is harder to understand.
> b<-1:10
> b[1:2]
[1] 1 2
> b[1]

[1] 1
> b[[1]]

[1] 1

         -thomas



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 Wed Oct 25 07:41:03 2006

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 Wed 25 Oct 2006 - 16:30:14 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.