R/exported_functions.R

Defines functions get_f_exp_from_points get_f_from_points get_slope

Documented in get_f_exp_from_points get_f_from_points get_slope

#' Get the slope between two points
#'
#' Simple helper function to compute slope between two cartesian points
#'
#' @param a a vector containing two (and only two) points corresponding to \eqn{x} and \eqn{y}.
#' @param b a vector containing two (and only two) points corresponding to \eqn{x} and \eqn{y}.
#'
#' @export
#'
#' @return slope value
#' @examples
#' get_slope(c(0, 0), c(1, 3))
get_slope <- function(a, b) {
  stopifnot(length(a) == 2, length(b) == 2, class(a)[1] == "numeric", class(b)[1] == "numeric")
  (b[2] - a[2]) / (b[1] - a[1])
}



#' Get the function of a line from two points
#'
#' `get_f_from_points()` returns a function that can be used to generate any points on a given line.
#'
#' @param a a vector containing two (and only two) points corresponding to \eqn{x} and \eqn{y}.
#' @param b a vector containing two (and only two) points corresponding to \eqn{x} and \eqn{y}.
#'
#' @export
#'
#' @return a function that returns $y$ for any $x$ on the line.
#' @examples
#' get_f_from_points(c(0, 0), c(1, 3))
get_f_from_points <- function(a, b) {
  stopifnot(length(a) == 2, length(b) == 2, class(a)[1] == "numeric", class(b)[1] == "numeric")
  slope <- get_slope(a, b)
  f <- function(x) slope * x - (slope * a[1]) + a[2]
}

#' Get the cubic function of a line from two points
#'
#' `get_f_exp_from_points()` returns a function that can be used to generate any points on a given line according to the specified exponential.
#'
#' @param a a vector containing two (and only two) points corresponding to \eqn{x} and \eqn{y}.
#' @param b a vector containing two (and only two) points corresponding to \eqn{x} and \eqn{y}.
#' @param power the desired exponential
#'
#' @export
#'
#' @return a function that returns $y$ for any $x$ on the line.
#' @examples
#' get_f_exp_from_points(c(0, 0), c(1, 3))
get_f_exp_from_points <- function(a, b, power = 3) {
  stopifnot(length(a) == 2, length(b) == 2, class(a)[1] == "numeric", class(b)[1] == "numeric")
  x1 <- a[[1]]
  x2 <- b[[1]]
  y1 <- a[[2]]
  y2 <- b[[2]]
  function(x) ((y2 - y1) / (x2^power - x1^power)) * x^power + y1 - (y2 - y1) / (x2^power - x1^power) * x1^power
}
firthj/oneliners documentation built on June 29, 2022, 11:19 p.m.