File: shift.R

package info (click to toggle)
r-cran-forcats 1.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 900 kB
  • sloc: makefile: 2
file content (32 lines) | stat: -rw-r--r-- 803 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#' Shift factor levels to left or right, wrapping around at end
#'
#' This is useful when the levels of an ordered factor are actually cyclical,
#' with different conventions on the starting point.
#'
#' @param f A factor.
#' @param n Positive values shift to the left; negative values shift to
#'   the right.
#' @export
#' @examples
#' x <- factor(
#'   c("Mon", "Tue", "Wed"),
#'   levels = c("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"),
#'   ordered = TRUE
#' )
#' x
#' fct_shift(x)
#' fct_shift(x, 2)
#' fct_shift(x, -1)
fct_shift <- function(f, n = 1L) {
  check_factor(f)
  check_number_whole(n)

  lvls_reorder(f, shift(nlevels(f), n))
}

shift <- function(m, n) {
  stopifnot(is.numeric(m), length(m) == 1L)
  stopifnot(is.numeric(n), length(n) == 1L)

  ((seq_len(m) - 1) + n) %% m + 1
}