[R] a sequence that wraps around
William Dunlap
wdunlap at tibco.com
Wed Sep 16 17:44:07 CEST 2009
> -----Original Message-----
> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of Jack Tanner
> Sent: Wednesday, September 16, 2009 7:08 AM
> To: r-help at stat.math.ethz.ch
> Subject: [R] a sequence that wraps around
>
> 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.
The remainder (modulus) operator, x%%n, wraps to the range 0..n-1
but you can write a function that wraps to 1..n as
mod1 <- function(x, n) (x-1L)%%n + 1L
Then pass the output of seq through that:
> mod1(-2:10, 3)
[1] 1 2 3 1 2 3 1 2 3 1 2 3 1
Bill Dunlap
TIBCO Software Inc - Spotfire Division
wdunlap tibco.com
>
> ______________________________________________
> 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.
>
More information about the R-help
mailing list