[R] problem with putting objects in list

Tony Plate tplate at acm.org
Wed Sep 6 20:11:19 CEST 2006

```I suspect you are not thinking about the list and the
subsetting/extraction operators in the right way.

A list contains a number of components.

To get a subset of the list, use the '[' operator.  The subset can
contain zero or more components of the list, and it is a list itself.
So, if x is a list, then x is a list containing a single component.

To extract a component from the list, use the '[[' operator.  You can
only extract one component at a time.  If you supply a vector index with
more than one element, it will index recursively.

> x <- list(1,2:3,letters[1:3])
> x
[]
 1

[]
 2 3

[]
 "a" "b" "c"

> # a subset of the list
> x[2:3]
[]
 2 3

[]
 "a" "b" "c"

> # a list with one component:
> x
[]
 2 3

> # the second component itself
> x[]
 2 3
> # recursive indexing
> x[[c(2,1)]]
 2
> x[[c(3,2)]]
 "b"
>

Rainer M Krug wrote:
> Hi
>
> I use the following code and it stores the results of density() in the
> list dr:
>
> dens <- function(run) { density( positions\$X[positions\$run==run], bw=3,
> cut=-2 ) }
> dr <- lapply(1:5, dens)
>
> but the results are stored in dr[[i]] and not dr[i], i.e. plot(dr[])
> works, but plot() doesn't.
>
> Is there any way that I can store them in dr[i]?
>
> Thanks a lot,
>
> Rainer
>
>
>

```