Skip to content

Instantly share code, notes, and snippets.

@imadmali
Created October 30, 2018 01:42
Show Gist options
  • Select an option

  • Save imadmali/3a6d4a5c8309316c6256cfcb925e5745 to your computer and use it in GitHub Desktop.

Select an option

Save imadmali/3a6d4a5c8309316c6256cfcb925e5745 to your computer and use it in GitHub Desktop.
Recursive function example in R
#' Sum of Vector (Recursive Function)
#' A recursive function to find the total sum of all the elements of a vector.
#' Logic: Sum any two elements of the vector. Concatenate this sum to the
#' vector, excluding the elements used to compute the sum. Pass this new vector
#' back into the function (the length should be the original length of the
#' vector minus 1). Terminate the recursion when the length of the vector is 1
#' (i.e. the total sum).
#' @param n A vector of numbers.
#' @return The sum of the vector.
recursive_add <- function(n) {
if (!is.vector(n) | !is.numeric(n))
stop("'n' must be a vector.", call. = FALSE)
if (length(n) > 1) {
x <- n[1] + n[2]
n <- c(x, tail(n, n=-2))
return(recursive_add(n))
}
return(n)
}
# example
recursive_add(1:10) == sum(1:10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment