R/fun_rec_seq.R

Defines functions fun_rec_seq

Documented in fun_rec_seq

#' Recursive Sequence Function
#'
#' A recursive sequence where element n is the sum of element n-1 and the
#' difference between elements n-2 and n-3 divided by n.
#'
#' @param x Numeric vector containing the first three elements of the sequence.
#' @param n Integer denoting the final nth element of the sequence.
#'
#' @return Returns element n.
#' @export fun_rec_seq
#'
#' @examples
#' fun_rec_seq(x = c(2, 4, 3), n = 3)
#' fun_rec_seq(x = c(2, 4, 3), n = 4)
#' fun_rec_seq(x = c(2, 4, 3), n = 5)

fun_rec_seq <- function(x, n){
  # Checks that parameter x is length 3 and numeric, and that parameter n is
  # positive and numeric
  stopifnot(length(x) == 3,
            is.numeric(x),
            n > 0,
            is.numeric(n))

  # Creates empty vector x_vec, and fills first three values from parameter x
  x_vec <- vector(mode = "numeric", length = n)
  x_vec[1] <- x[1]
  x_vec[2] <- x[2]
  x_vec[3] <- x[3]

  # For loop to calculate recursive sequence
  for (i in seq_along(x_vec)){
    if (i > 3 & n > 3) {
      x_vec[i] <- x_vec[i-1] +
        (x_vec[i-3] - x_vec[i-2])/i
    } else if (n == 1){
      return(x_vec[n])
    } else if (n == 2){
      return(x_vec[n])
    } else if (n == 3){
      return(x_vec[n])
    }
  }
  return(x_vec[n])
}
21Sp-STAT-413-613/hw04p.marc.estevadeordal documentation built on March 1, 2021, midnight