简体   繁体   中英

statistical moments in R

I've got a data set in R of a variable, repeated 10,000 times and sampled 200 times on each repeat so a 10,000 by 200 matrix, I would like to calculate statistical moments for the variable up to an arbitrary number. So in the end I would like a numeric vector holding the value of moments.

I can get the variance and the mean for the data set using colMean and colVar, but they only go so far.

I am also aware of the moments package in R, however using the all.moments command is returning me moments for each time course, or treating each column or row as an individual variable, not what I want.

Does anyone know an equivalent to colMean and colVar for higher order moments? And if possible also for cross moments?

Many thanks!

I stole this code from an obscure R package e1071 :

theskew<- function (x) {
x<-as.vector(x)
 sum((x-mean(x))^3)/(length(x)*sd(x)^3)
 }
thekurt <- function (x) {
x<-as.vector(x)
  sum((x-mean(x))^4)/(length(x)*var(x)^2) - 3
  }

You can fold that into your code by feeding them one column at a time

Okay did this yesterday for posterity here is a loop that will do what I asked.

Provided your data is a time course of a variable you are measuring, and you want the moments of that variable:

rm(list=ls())

yourdata<-read.table("whereveryourdatais/and/variableyouwant")

yourdata<-t(yourdata) #only do this at your own discretion


mu<-colMeans(yourdata,1:ncol(yourdata))

NumMoments <- 5
rawmoments <- matrix(NA, nrow=NumMoments, ncol=ncol(yourdata))

for(i in 1:NumMoments) {
  rawmoments[i, ] <- colMeans(yourdata^i)
}
plot(rawmoments[1,])

holder<-matrix(NA,nrow=nrow(yourdata),ncol=ncol(yourdata))
middles<-matrix(NA,nrow=1,ncol=ncol(yourdata))

for(j in 1:nrow(yourdata)){
  for(o in 1:ncol(rawmoments)){
    middles[o]<-yourdata[j,o]-rawmoments[1,o]
  }
  holder[j,] <- middles 
}
centmoments<-matrix(NA,nrow=NumMoments,ncol=ncol(yourdata))


for(i in 1:NumMoments){
  centmoments[i,]<-colMeans(holder^i)
}

Then centmoments has the centralmoments and rawmoments has the raw moments, you can specify how many moments to take by changing the value of NumMoments. Note that the first row in "centmoments" will be approximately 0.

Is this what you're looking for?

X <- matrix(1:12, 3, 4) # your data

NumMoments <- 5
moments <- matrix(NA, nrow=NumMoments, ncol=ncol(X))

for(i in 1:NumMoments) {
  moments[i, ] <- colMeans(X^i)
}

EDIT: okay, apparently you want "central moments"

X <- matrix(1:12, 3, 4)

NumMoments <- 5
moments <- matrix(NA, nrow=NumMoments, ncol=ncol(X))

Y <- X

for(i in 1:ncol(X)) {
  Y[, i] <- Y[, i] - moments[1, i]
}

for(i in 2:NumMoments) {
  moments[i, ] <- colMeans(Y^i)
}

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