[R] a sequence that wraps around

Szabolcs Horvát szhorvat at gmail.com
Wed Sep 16 16:49:51 CEST 2009


On 2009.09.16. 16:08, 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.
>

Disclaimer: total R beginner here (started to learn a 1 day ago), who 
just came to this list to learn.

You could use the modulo operator.

> # 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=1, length.out=4) %% 3 + 1

> seq(from=2, length.out=4, rlimit=4)
> [1] 2 3 4 1

seq(from=1, length.out=4) %% 4 + 1

> seq(from=2, length.out=3, rlimit=2)
> [1] 2 1 2

seq(from=1, length.out=3) %% 2 + 1

(the 'from' needed to be decreased by one, otherwise it'd start from 0)

>
> 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.
>




More information about the R-help mailing list