[R] a sequence that wraps around

Duncan Murdoch murdoch at stats.uwo.ca
Wed Sep 16 17:51:37 CEST 2009


On 9/16/2009 10:08 AM, Jack Tanner wrote:
> I'd like to have something like seq() where I can pass in a length of the
> desired sequence and a right limit so that the sequence goes up to the limit and
> then starts again from 1.
> 
> # works now
> seq(from=2, length.out=3)
> [1] 2 3 4
> 
> # what I want
> seq(from=2, length.out=3, rlimit=3)
> [1] 2 3 1
> 
> # additional examples of what I want
> seq(from=2, length.out=4, rlimit=3)
> [1] 2 3 1 2
> seq(from=2, length.out=4, rlimit=4)
> [1] 2 3 4 1
> seq(from=2, length.out=3, rlimit=2)
> [1] 2 1 2
> 
> I can write this procedurally, but it seems like there ought to be a cleaner R
> way of doing it. Thanks in advance for any suggestions.

Here's a start.  You probably want some sanity checks on the arguments; 
e.g. from=1 doesn't work because of the old 1:0 infelicity.

seq2 <- function(from, length.out, rlimit)
   rep(1:rlimit, length.out=length.out+from-1)[-(1:(from-1))]

Duncan Murdoch




More information about the R-help mailing list