Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate the following sequence without resorting to a loop?

Tags:

r

time<-c(10,20)
d<-NULL
for ( i in seq(length(time)))
d<-c(d,seq(0,(time[i]-1)))
d

When time<-c(3000,4000,2000,...,5000) and the length of time is 1000, the procedure is very slow. Is there a faster way generating the sequence without looping?

Thanks for your help.

like image 782
Tony Avatar asked Mar 25 '11 14:03

Tony


1 Answers

Try d <- unlist(lapply(time,function(i)seq.int(0,i-1)))

On a sidenote, one thing that slows down the whole thing, is the fact that you grow the vector within the loop.

> time<-sample(seq(1000,10000,by=1000),1000,replace=T)

> system.time({
+  d<-NULL
+  for ( i in seq(length(time)))
+  d<-c(d,seq(0,(time[i]-1)))
+  }
+ )
   user  system elapsed 
   9.80    0.00    9.82 

> system.time(d <- unlist(lapply(time,function(i)seq.int(0,i-1))))
   user  system elapsed 
   0.00    0.00    0.01 

> system.time(unlist(mapply(seq, 0, time-1)))
   user  system elapsed 
   0.11    0.00    0.11 

> system.time(sequence(time) - 1)
   user  system elapsed 
   0.15    0.00    0.16 

Edit : added timing for other solutions as well

like image 191
Joris Meys Avatar answered Nov 12 '22 00:11

Joris Meys