简体   繁体   中英

Calculating Sample Moments in R (raw code)

I'm trying to code functions that will calculate sample moments around 0 and around the mean, from the 1st order to the 4th order. I got the first one down, but I am having trouble with the second. Here's my code:

moment.zero <- function(x) {
  lapply(1:4, function(i) (1/length(x$elements)) * sum(x$elements^i))
}

moment.mean <- function(x) {
  lapply(1:4, function(i) (1/length(x$elements)) * sum(x$elements #mistake is here - mean(x$elements))^i)
}

I am not supposed to use loops, so I used the lapply function. I can't figure out the code for the sample moment around the mean; I need to access each individual element in the list, subtract it from the mean, then raise it to the appropriate power. Using indices did not help, so my main question is: how does one refer to each element within a list?

moment.zero <- function(x) {
  n <- length(x)
  sapply(1:4, function(i) (1/n) * sum(x^i))
}

moment.mean <- function(x) {
  mu <- mean(x)
  n <- length(x)
  sapply(1:4, function(i) (1/n) * sum((x - mu)^i))
}

Note that calculating mu and n up front is a (minor) efficiency improvement - otherwise they are calculated four times.

To reference elements of a vector use square brackets: eg x[2] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM