CalculateSampleMomentAroundZero <- function(x) {
# Computes the sample moments (up to fourth order) around zero
#
# Args:
# x: A vector of numbers whose sample moments around zero
# will be calculated
#
# Returns:
# A list that contains the sample moments (up to fourth order)
# of the numbers in vector x.
n <- length(x)
moment.zero <- lapply(1:4, function(i) (1/n) * sum(x^i))
names(moment.zero) <- c("first", "second", "third", "fourth")
moment.zero
}
CalculateSampleMomentAroundMean <- function(x) {
# Computes the sample moment (up to fourth order) around the mean
#
# Args:
# x: A vector of numbers whose sample moments around the mean
# will be computed
#
# Returns:
# A list that contains the sample moments (up to fourth order)
# of the numbers in vector x.
#
# Uses the function to calculate sample moments around zero to
# obtain the mean (sample moment around zero of first order) of
# the numbers in vector x.
#
moments.around.zero <- CalculateSampleMomentAroundZero(x)
xbar <- moments.around.zero$first
n <- length(x)
moment.mean <- lapply(1:4, function(i) (1/n) * sum((x - xbar)^i))
names(moment.mean) <- c("first", "second", "third", "fourth")
moment.mean
}
skewnesskurtosis <- function(x) {
# Computes the skewness and kurtosis of a vector of numbers
#
# Args:
# x: A vector of numbers whose skewness and kurtosis will be
# computed.
#
# Returns:
# A list that contains the skewness and kurtosis of the numbers
# in vector x.
#
# Uses the function to compute sample moments around the mean to
# obtain the second, third, and fourth orders of the sample
# moments around the mean.
#
moments.around.mean <- CalculateSampleMomentAroundMean(x)
mu2 <- moments.around.mean$second
mu3 <- moments.around.mean$third
mu4 <- moments.around.mean$fourth
skew <- mu3 / (mu2)^(3/2)
kurt <- (mu4 / (mu2)^(2)) - 3
sk <- list(skewness = skew, kurtosis = kurt)
sk
}
我使用时刻库中的函数检查了我的输出,我的第一个函数得到了相同的结果。然而,第二个功能有点奇怪。第二个、第三个和第四个时刻匹配,但第一个不匹配。这很奇怪,因为第一时刻怎么可能是不正确的,而其余的时刻是正确的?我多次查看我的代码,但我仍然找不到错误。有人可以帮忙吗?
编辑:这是我的输入和输出
x <- rnorm(5)
CalculateSampleMomentAroundMean(x)
$first
[1] -2.220446e-17
$second
[1] 0.2923308
$third
[1] -0.02291481
$fourth
[1] 0.1172637
> moment(x, order = 1, central = TRUE)
[1] -8.326673e-18
> moment(x, order = 2, central = TRUE)
[1] 0.2923308
> moment(x, order = 3, central = TRUE)
[1] -0.02291481
> moment(x, order = 4, central = TRUE)
[1] 0.1172637