[R] Vectors of objects...

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Nov 19 17:53:46 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.

You can't.  Vectors are atomic, except for lists (also known as
generic vectors).  You can do

mega <- vector("list", 2)
names(mega) <- 1:2
mega[[1]] <- object
mega[[2]]<- object2

$"1"
$"1"$a
[1] "test"

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


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

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

[...]

You accidentally overwrote an integer vector by a list in the [...]

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

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