[R] sequence with start and stop positions

Charles C. Berry cberry at tajo.ucsd.edu
Tue Aug 26 19:12:28 CEST 2008


On Tue, 26 Aug 2008, Chris Oldmeadow wrote:

> Hi,
>
> I have a vector of start positions, and another vector of stop positions,
>
> eg start<-c(1,20,50)
>     stop<-c(7,25,53)
>
> Is there a quick way to create a sequence from these vectors?
>
> new<-c(1,2,3,4,5,6,7,20,21,22,23,24,25,50,51,52,53)


Vectorize the process.

> start2 <- rep( start, stop-start+1 )
> lens <- stop-start+1
> offset <- rep(cumsum(c( 0, lens )),c( lens ,0 ))
> seq(along=offset)-offset+start2-1
  [1]  1  2  3  4  5  6  7 20 21 22 23 24 25 50 51 52 53
>

HTH,

Chuck

>
> the way Im doing it at the moment is
>
> pos<-seq(start[1],stop[1])
>
> for (i in 2:length(start)){
>  new<-seq(start[i],stop[i])
>  pos<-c(pos,new)
> }
>
> This works on small data, but its very inefficient on large vectors, and is 
> taking forever!
>
> Anybody no a better way?
>
> many thanks,
> Chris
>
> ______________________________________________
> R-help at r-project.org 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.
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901



More information about the R-help mailing list