[R] the secret (?) language of lists

Peter Dalgaard p.dalgaard at biostat.ku.dk
Tue Nov 14 23:51:11 CET 2006


Jeffrey Robert Spies <jspies at nd.edu> writes:

> A couple days ago, Mark Leeds asked about a solution that would  
> basically stagger two lists, a and b, to return a list in the form of  
> a[1], b[1], a[2], b[2], a[3]....  In particular, the summary of his  
> question was in reference to lists defined by
> 
>   x <- 5
>   tempin <- seq(1,1411, by=30)
>   a <- tempin
>   b <- tempin + x
> 
> I offered the following function
> 
>   everyOther <- function(tempin, x){
>   	tempout <- array(data=NA, dim=length(tempin)*2)
>   	tempout[seq(1,length(tempin)*2, by=2)]<-tempin
>   	tempout[seq(2,length(tempin)*2, by=2)]<-tempin+x
>   	tempout
>   }
> 
> which did what it was supposed to, and Gavin Simpson offered a  
> similar function.  Peter Dalgaard, however, supplied a much more  
> elegant solution:
> 
>   c(rbind(tempin,tempin+5))
> 
> or
> 
>   rep(tempin, each=2) + c(0,5)
> 
> I thought I'd bring this up as a new topic because it's really no  
> longer related to what Mark first asked, but is there a way, perhaps  
> from the documentation, that a user would know that c() and lists in  
> general behave as they do in these two lines?  Or would we just need  
> to dig into the code?

(What lists? I see only vectors. Lists in R is a different kind of object.)  

There are a few basic principles in play here, once you know them, the
rest follows; I'm not sure exactly where they are documented, but I'd
guess at Venables & Ripley's books (MASS, S Programming) at least, the
"Blue Book" on S, and possibly others.

The first suggestion requires that you know or now about the following

- matrices are vectors with dim attibutes, stored column-major
— binding rows into matrices with rbind()
- c() removes attributes

The second one requires

- rep function, and its each=
- vector recycling in arithmetic
 
> I am reminded of quote by Byron Ellis: "Contrary to popular belief  
> the speed of R's interpreter is rarely the limiting factor to R's  
> speed. People treating R like C is typically the limiting factor. You  
> have vector operations, USE THEM."  Not exactly the point, but close.
> 
> Thanks!
> 
> Jeff Spies
> http://www.nd.edu/~jspies/
> 
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list