# [R] list index rules evaluation behavior

David Winsemius dwinsemius at comcast.net
Tue Mar 30 18:55:18 CEST 2010

```On Mar 30, 2010, at 11:47 AM, Dgnn wrote:

>
> I have what may be a simple/foolish question, but I've done the due
> diligence
> and looked through pages of posts here as well as several of the
> PDFs on the
> CRAN site, but haven't been able find what I'm after.
>
> I am working with a list of say 3 histogram objects A, B & C, and each
> histogram is a list of 7 elements. I would like to access \$name, the
> 6th
> element, of histograms A,B and C.
>

If you want better answers, you should provide better examples ...
with _CODE_.

>
> Trial and error yielded some results that told me I clearly don't
> understand
> how R interprets index commands. For the histogram list above:
> a[1:2] give histograms A and B as expected.
> a[[1:2]] gives the second element of histogram 1, but a[[1:1]] gives
> all
> elements of histogram 1, while a[[1:3]] gives null?!
>
> If anyone could help with an explanation of indexing rules, or a
> source that
> does so, I would very much appreciate it. Oh and an answer to the
> first
> question!

?"[["

"[[" always returns a single vector or list and so its arguments will
be coerced to a single value. When passed an arguemnt that has
multiple values it is interpreted as serial application of "[[" with
the serial values.  The construction [[1:1]] gets turned into [[1]]
(since 1:1 is just 1)  while the construction [[1:2]] got turned into
[[1]][[2]]

> list(a=list(aa=5, bb=6),b=2,c=3)[[1:2]]
[1] 6

"[" may return a more complex object and so may accept multiple
arguments

> list(a=1,b=2,c=3)[c(1,3)]
\$a
[1] 1

\$c
[1] 3

>
--

David Winsemius, MD
West Hartford, CT

```