Is there a simple, base r approach to create a sequence of numbers from a broader REPEATING set? For instance, thinking of months of the year, how can I create a sequence based on start /end months such that:
>fx(5:10)
5, 6, 7, 8, 9, 10
but also that
>fx(10:3)
10, 11, 12, 1, 2, 3
I know this is possible based on a few lines of inelegant code, but I am sure there is something simple and concise out there.
CodePudding user response:
This isn't very elegant, but it is a single line that does the trick, as long as the sequence is a set of integers from 1:m
.
fx <- function(f, l, m) (y <- (1:m)[c(f:m, 2:f - 1)])[1:which(y == l)]
> fx(5, 10, m = 12)
[1] 5 6 7 8 9 10
> fx(10, 3, m = 12)
[1] 10 11 12 1 2 3
CodePudding user response:
One option using the modulo:
f <- function(start, end, max) (seq(start, end (end < start) * max) - 1) %% max 1
f(5, 10, 12)
[1] 5 6 7 8 9 10
f(10, 3, 12)
[1] 10 11 12 1 2 3