简体   繁体   English

计算R中的样本矩(原始代码)

[英]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. 我正在尝试对函数进行编码,这些函数将计算从1阶到4阶在0和均值附近的样本矩。 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. 我不应该使用循环,所以我使用了lapply函数。 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. 请注意,预先计算mun是(较小的)效率改进-否则它们将被计算四次。

To reference elements of a vector use square brackets: eg x[2] . 要引用向量的元素,请使用方括号:例如x[2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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