# [R] [] vs [[]]

Jan Goebel jgoebel at diw.de
Fri Oct 20 13:06:47 CEST 2000

```On Fri, 20 Oct 2000, Bill Simpson wrote:

> I have read over Venables and Ripley and am still confused about [] vs
> [[]]. I had thought it was simple: use [] for accessing items in a vector,
> and [[]] for items in a list.
>
> Vector
> > x<-1:10
> > x[4]
> [1] 4
> > x[[4]]
> [1] 4
> doesn't seem to matter if you use [] or [[]]

In this special case yes (IMHO)

>
> List
> > x<-list(1,2,3,4)
> > x[2]
> [[1]]
> [1] 2
>
> > x[[2]]
> [1] 2
> doesn't seem to matter if you use [] or [[]]

No, it does matter:

> x<-list(1,2,3,4)
> is.list(x[2])
[1] TRUE
> is.list(x[[2]])
[1] FALSE
> is.vector(x[[2]])
[1] TRUE

Using [] with a list you get a list, using [[]] you get
the item of these "sublist".

But be aware off:

> testlist<- list(list(cbind(1:4,1:4),1:5,"any.item"))
> testlist[1]
[[1]]
[[1]][[1]]
[,1] [,2]
[1,]    1    1
[2,]    2    2
[3,]    3    3
[4,]    4    4

[[1]][[2]]
[1] 1 2 3 4 5

[[1]][[3]]
[1] "any.item"

>>> returns a list, as usual

> testlist[[1]]
[[1]]
[,1] [,2]
[1,]    1    1
[2,]    2    2
[3,]    3    3
[4,]    4    4

[[2]]
[1] 1 2 3 4 5

[[3]]
[1] "any.item"

>>> returns also a list!

> testlist[[1]][[1]]
[,1] [,2]
[1,]    1    1
[2,]    2    2
[3,]    3    3
[4,]    4    4

returns the matrix!

Hope there are no more obscurity than before.

jan

--
-----------------------------------
Jan Goebel (mailto:jgoebel at diw.de)

DIW German Institute for Economic Research
SOEP
Königin-Luise-Str. 5
D-14195 Berlin
Germany

phone: 49 30 89789-377
-----------------------------------
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```