[R] apply() question

Robin Hankin rksh at soc.soton.ac.uk
Thu Oct 16 14:53:06 CEST 2003


Hi

I have a function that returns an array with four columns but the
number of rows differs with the calling argument.  I want to use
something like sapply() to rbind() the outputs together.

Following toy example illustrates my problem:

f  <- function(i) {
   options(warn= -1)
   r <- ceiling(sqrt(i))
   return(matrix(1:3,r,4))
}

Thus sapply(1:5,f) is a list with five elements.

R> (a <- sapply(1:5,f))
[[1]]
      [,1] [,2] [,3] [,4]
[1,]    1    2    3    1

#{...DELETED...}

[[5]]
      [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    2    2    2    2
[3,]    3    3    3    3

R>

what I want is the equivalent of

R> rbind(a[[1]],a[[2]],a[[3]],a[[4]],a[[5]])

but with an arbitrary upper limit and without any loops.  Anyone?


Obligatory attempt:
R> string<-paste("jj<-rbind(a[[1]] ",paste(",a[[",2:5,"]]",collapse=" "),")")
R> eval(parse(text=string))




More information about the R-help mailing list