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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With