R/triangle.R

#' An S3 class to represent a triangle
#' Triangle
#'
#' @param x a numerical vector of 3 sides
#'
#' @return A triangle object with 3 sides .
#' @export
#' @examples triangle(c(1,4,7))
triangle <- function(x) {
  if (!is.numeric(x)) stop("X must be a numeric vector with 3 positive values")
  if (!(length(x) == 3)) stop("you must put in only 3 sides")
  if (!(x[1] > 0 & x[2] > 0 & x[3] > 0)) stop("all side lengths must be greater than 0")
  structure(c(x), class = "triangle")
}

#' Generic for Area
#'
#' @param x, a triangle object
#'
#' @export
#'
area <- function(x) {
  UseMethod("area")
}


#' triangle area() function
#'
#' @param x, a triangle object
#'
#' @return The aree of triangle with sides \code{side1}, \code{side2}, \code{side3}.
#' @export
#'
#' @examples area(my_triangle)
area.triangle <- function(x) {
  # calculate the semi-perimeter
  a = x[1]
  b = x[2]
  c = x[3]
  s = (a + b + c) / 2

  # calculate the area
  area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
  return(area)
}


#' Sin generic
#'
#' @param x, a triangle object
#'
#' @export
#'
sin <- function(x) {
  UseMethod("sin")
}

#' triangle sine() function
#'
#' @param x triangle object
#'
#' @return the sin of the triangle \code{side2} divided by \code{side3}.
#' @export
#'
#' @examples sin(my_triangle)
sin.triangle <- function(x) {
  # calculate the sin
  return(x[2]/x[3])
}
kitsonswann/triangle documentation built on May 20, 2019, 10:25 a.m.