We wish to cacluate the skewness and kurtosis of a general vector using R. First, we must load the package VGAM to be used for testing our function later. We also set a seed so that our code can be replicated precisely when tested by others.
library(VGAM)
set.seed(54321)
The first step in calculating the skewness and kurtosis is being able to solve for the first four moments of a vector. We first calculate these moments centered around 0.
Mu.0 <- function (vector) {
# Calculates the moments around 0.
#
# Args:
# vector: the vector which you wish to calculates the moments of.
#
# Returns:
# A vector containing the first four moments centered around 0.
mu <- c()
mu[1] <- sum(vector^1) / length(vector)
mu[2] <- sum(vector^2) / length(vector)
mu[3] <- sum(vector^3) / length(vector)
mu[4] <- sum(vector^4) / length(vector)
return(mu)
}
Having calculated the moments around 0, we now calculate the moments centered around the mean.
Mu.Mean <- function (vector) {
# Calculates the moments around the mean.
#
# Args:
# vector: the vector which you wish to calculates the moments of.
#
# Returns:
# A vector containing the first four moments centered around the mean.
mu <- c()
mu1 <- sum(vector) / length(vector) # Calculates the Mean
mu[1] <- sum((vector - mu1)^1) / length(vector)
mu[2] <- sum((vector - mu1)^2) / length(vector)
mu[3] <- sum((vector - mu1)^3) / length(vector)
mu[4] <- sum((vector - mu1)^4) / length(vector)
return(mu)
}
Using our moments function centered around the mean, we can now calculate the skewness as well as the kurtosis.
Kurt.Skew <- function(vector) {
# Calculates the skewness and kurtosis.
#
# Args:
# vector: the vector which you wish to calculates the skewness and kurtosis of.
#
# Returns:
# A list containing the skewness and the kurtosis.
#
# Calculating skewness
skew <- Mu.Mean(vector)[3] / ((Mu.Mean(vector)[2])^(3 / 2))
# Calculating kurtosis
kurt <- (Mu.Mean(vector)[4] / (Mu.Mean(vector)[2]^2)) - 3
l <- list(Skewness = skew, Kurtosis = kurt)
return(l)
}
We can now test our function by using randomly generated numbers which follow specific distributions. Here we use the normal, Cauchy, Laplace, and Chi-Squared distributions.
try1 <- Kurt.Skew(rnorm(9999))
try2 <- Kurt.Skew(rcauchy(9999))
try3 <- Kurt.Skew(rlaplace(9999))
try4 <- Kurt.Skew(rchisq(9999, df=123))
We now place the results of our tries above into the table below for closer examination.
| Distribution | Skewness | Kurtosis |
|---|---|---|
| Normal | -0.0472 | -0.0559 |
| Cauchy | 66.1069 | 5935.0144 |
| Lapace | 0.146 | 2.8904 |
| Chi-Square | 0.2793 | 0.3219 |