Writing functions - Crazything

(This practice is what crazy Dung asked me to do)

  1. Function to calculte the mean of the sample
mean_x <- function(x) {M = sum(x)/length(x); M}
x <- c(1,2,3,4,5)
mean_x(x)
## [1] 3
  1. Function to calculate the skewness of the sample
variance <- function(x) {
    n <- length(x)
    m <- mean(x)
    (1/(n - 1)) * sum((x - m)^2)
}

skewness <- function(x) {
    n <- length(x)
    v <- var(x)
    m <- mean(x)
    third.moment <- (1/(n - 2)) * sum((x - m)^3)
    third.moment/(var(x)^(3/2))
}
x <- c(1:10)
skewness(x)
## [1] 0
variance(x)
## [1] 9.166667
a <- c(2,5,-1,3,4,5,0,2)
mean_x(a)
## [1] 2.5
skewness(a) 
## [1] -0.3736704
variance(a)
## [1] 4.857143