[R] code speed help? -- example and results provided
Jerome Asselin
jerome at hivnet.ubc.ca
Tue Aug 5 21:05:40 CEST 2003
It doesn't seem that you need data frame to do this since x1 and x2 are
always numeric. I think your final data frame object has N rows.
This should be much faster.
n <- 5
N <- 10
life <- c(3,2,7,8,10)
ind <- N-life
matrix(rep(rep(0:1,n),c(rbind(life,ind))),ncol=N,byrow=T)
BTW, it would have been easier to help if you had put your executable
example ready to "cut and paste". All the ">" and "+" make it tedious to
reproduce your example.
HTH,
Jerome
On August 5, 2003 11:28 am, Debruicker, Paul Andrew wrote:
> I have the following piece of code that combines lists comprised of
> components of varying length into a list with components of constant
> length. I have found 2 ways to do it, and the faster of the two is
> posted below along with sample results. Do you have any suggestions on
> how to decrease the calculation time by modifying the code?
>
> > ####Function###########
> > replacement2.idx<-function(life=w.life,N=years,n=samples){
>
> +
> + yrs<-rep(N,n)
> + ind<-yrs-life
> +
> + x1<-mapply(rep,times=life,x=0)
> + x2<-mapply(rep,times=ind,x=1)
> +
> + x3<-data.frame(c(x1[[1]],x2[[1]]))
> +
> + for(i in 2:n) x3<-data.frame(x3, append(x1[[i]],x2[[i]]))
> +
> + x3<-t(x3)
> + }
>
> > ###Sample Output###
> > samples<-5
> > years<-10
> > w.life<-round(rnorm(samples,5,1),digits=0)
> >
> > system.time(abc<-replacement2.idx())
>
> [1] 0.04 0.00 0.07 0.00 0.00
>
> > abc
>
> 1 2 3 4 5 6 7 8 9 10
> c.x1..1....x2..1... 0 0 0 0 0 0 1 1 1 1
> append.x1..i....x2..i... 0 0 0 0 0 0 1 1 1 1
> append.x1..i....x2..i... 0 0 0 0 0 0 1 1 1 1
> append.x1..i....x2..i... 0 0 0 0 1 1 1 1 1 1
> append.x1..i....x2..i... 0 0 0 0 0 1 1 1 1 1
>
> > ###1000 samples####
> > samples<-1000
> > w.life<-round(rnorm(samples,5,.5),digits=0)
> > system.time(method2<-replacement2.idx())
>
> [1] 12.79 0.00 14.04 0.00 0.00
>
> > ###5000 samples####
> > samples<-5000
> > w.life<-round(rnorm(samples,5,.5),digits=0)
> > system.time(method2<-replacement2.idx())
>
> [1] 544.82 0.00 593.98 0.00 0.00
>
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
More information about the R-help
mailing list