R/recur_seq.R

Defines functions recur_seq

Documented in recur_seq

#' recur_seq
#' @description Computes a recursive sequence from three initial values and returns the nth element.
#' @param x Vector of three numbers
#' @param n Element of the sequence computed from x to return
#'
#' @return nth value of the sequence
#' @export
#'
#' @examples recur_seq(x = c(2, 4, 3), n = 10)
recur_seq <- function(x, n) {
  # Check conditions: numeric lenght-3 x and length-1 integer n
  if (!(is.numeric(x) && is.numeric(n))) {
    stop("Parameters of incorrect type")
  } else if (length(x) != 3 ||
             length(n) != 1 | n < 1 | n %% 1 != 0) {
    stop("Numerically invalid parameters")
  }

  #Early return if short sequence
  if (n <= 3) {
    return(x[n])
  }

  # Initialize  sequence
  init <- 4L
  x <- c(x, rep(0L, length.out = n - 3L))

  # Compute sequence
  for (i in seq(init, n)) {
    x[i] <- x[i - 1L] + ((x[i - 3L] - x[i - 2L]) / i)
  }
  x[[n]]
}
21Sp-STAT-413-613/hw04ryanheslin documentation built on Feb. 25, 2021, 2:56 p.m.