stat2/R/moments.R
2023-01-07 19:25:54 +01:00

61 lines
1.5 KiB
R

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#' moment: Calculate moment of vector
#'
#' Calculates the given standardised moment
#'
#' @param x A numeric vector for calculation
#' @param n Power of moment
#' @param central True if centralised moment (bool)
#' @param na.rm Remove NA-s
#'
#' @return n-th moment
#' @export
moment <- function(x, n = 1, central = T, na.rm = T){
if(central) {
sum((x-mean(x))^n/ sd(x,na.rm = na.rm)^n)
}else{
sum(x^n/ sd(x,na.rm = na.rm)^n)
}
}
#' skew: Calculate skewness of vector
#'
#' Calculates the 3rd standardised moment
#'
#' @param x A numeric vector for calculation
#' @param na.rm Remove NA-s
#'
#' @return Skewness
#' @export
skew <- function(x, na.rm = T){
moment(x,n=3,T,na.rm)
}
#' kurt: Calculate kurtosis of vector
#'
#' Calculates the 4rd standardised moment
#'
#' @param x A numeric vector for calculation
#' @param na.rm Remove NA-s
#'
#' @return Kurtosis
#' @export
kurt <- function(x, na.rm = T){
moment(x,n=4,T,na.rm)
}