[R] appending an R-object to a list

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Tue Apr 6 23:43:50 CEST 2010


On Tue, Apr 6, 2010 at 10:28 PM, David.Epstein
<David.Epstein at warwick.ac.uk> wrote:
>
> How do I append an R-object to a list?
> I want to start with an empty list, and append R-objects one by one.
> Does this start with a command like
> mylist <- NULL
> ??
>
> I have read a few answers on R-help to questions like this, but they all
> seem to be well off the point. Sometimes it's assumed that the list is a
> vector---not my case.
> One answer I read said that the object appended must be a list. This doesn't
> make sense to me. I don't want a list of lists. I want a list of R-objects.

Start with an empty list() and just assign to the next element:

 > z=list()
 > z[[1]]=c(1,2,3)
 > z[[2]]=c(9,5,4)
 > z
[[1]]
[1] 1 2 3

[[2]]
[1] 9 5 4

 - that's a "list of R objects", in this case the R objects are simple
vectors, but they could be any R objects - fitted models, spatial
point patterns etc etc. Is that what you want?

 You can also just add elements by name:

 z = list()
 z$foo = c(1,2,3)
 z$fnord = "hello"

z[[1]] and z[[2]] are also valid here.

Barry



More information about the R-help mailing list