[R] Vectors of objects...

Thomas Lumley tlumley at u.washington.edu
Mon Nov 19 17:57:07 CET 2001


On Mon, 19 Nov 2001, Randall Skelton wrote:

> Surely I am confused about something... still.  Having read parts of
> S-programming, MASS, and Programming with Data, I am no closer to
> understanding how to make a simple vector containing list objects. If I
> have somehow skipped over a relevant section in these books, please let me
> know what sections I should have read.  This is a simpler case of what I
> posted on Friday.  I am trying to build something in R that resembles an
> array of structures in C.
>
> > # Create some simple objects (ordinarily objects generated by a function)
> > object <- list(a="test", b=c(1.0,2.0,3.0,4.0))
> > object2 <- list(a="test2", b=c(2.0,4.0,6.0,8.0))
> > # Create a vector of length 2
> > mega <- 1:2
>
> At this point I want to insert object 1 into the first element of the
> vector 'mega' and object 2 into the second element.
>
> > mega[[1]] <- object
> Error: more elements supplied than there are to replace
> > print(mega)
> [1] 1 2
>
> No luck there...
>
> > mega[1] <- object
> Warning message:
> number of items to replace is not a multiple of replacement length
> > print(mega)
> [[1]]
> [1] "test"
>
> [[2]]
> [1] 2
>
> Still no luck... BUT, if I once again try:
>
> > mega[[1]] <- object
> > print(mega)
> [[1]]
> [[1]]$a
> [1] "test"
>
> [[1]]$b
> [1] 1 2 3 4
>
>
> [[2]]
> [1] 2
>
> Moreover,
>
> > mega[[2]] <- object2
> > print(mega)
> [[1]]
> [[1]]$a
> [1] "test"
>
> [[1]]$b
> [1] 1 2 3 4
>
>
> [[2]]
> [[2]]$a
> [1] "test2"
>
> [[2]]$b
> [1] 2 4 6 8
>
> Clearly I am missing something here.  The end result of 'mega' is exactly
> what I wanted in the first place, but it seems I needed to make 2 mistakes
> before I could get there?  Can someone please explain?


The problem is that you need mega to be a vector of mode `list'.  As it
happens,
   mega[1]<-object
coerces mega to mode list. You get a warning because you're trying to put
a whole list into a single element, and only the first element of object
ends up being assigned.  As you now have a vector of mode `list' the
proper assignment
  mega[[1]]<-object
works.

What you wanted was something like
> mega<-vector("list",2)
> mega[[1]]<-object
> mega[[2]]<-object2
> mega
[[1]]
[[1]]$a
[1] "test"

[[1]]$b
[1] 1 2 3 4


[[2]]
[[2]]$a
[1] "test2"

[[2]]$b
[1] 2 4 6 8

or
> mega<-list(1,2)
> mega[[1]]<-object
> mega[[2]]<-object2
would work just as well.

You can now extend the list by assigning to mega[[3]] if you like.

	-thomas


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list