[R] [FORGED] Re: Weighted skewness and curtosis

SEMson niels at ohlsen-web.de
Tue Sep 22 16:05:18 CEST 2015


I´m also looking for an answer on this question right now. 

You can´t use a weight in the moments package, but i found a
weighted.moments()-function in the acid-package ( weighted.moments-function
<https://github.com/cran/acid/blob/master/R/weighted.moments.R>  ). If your
data has NA, you can do the following:

#-----------------------------------------------------------------
skew <- function(x,weight){
  weight<-weight[!is.na(x)]  #delete weight for cases with NA
  x<-x[!is.na(x)]                 # delete NA
  acid::weighted.moments(x, w8=weight) #calulate moments
}
skew(mydata$var,weight)
#-----------------------------------------------------------------


I also tried to write a weighted-skew-function by myself:
The result is different from the acid-package: i get a skew of 0.7692313.
Perhaps, because x and length(x) aren´t weighted here. The unweighted skew
was 0.58 btw.
#-----------------------------------------------------------------
skew.wtd <- function(x,weight){
  weight<-weight[!is.na(x)]
  x<-x[!is.na(x)]
  sum.w <- sum(weight)
  sum.w2 <- sum(weight^2)
  mean.w <- sum(x * weight) / sum(weight)
  x.sd.w<-sqrt((sum.w / (sum.w^2 - sum.w2)) * sum(weight * (x - mean.w)^2))
  ((sum(((x - mean.w)/ x.sd.w)^3))/(length(x) - 1))
}
skew.wtd(mydata$var,weight)
#-----------------------------------------------------------------


Because the acid-package doesn´t give a weighted kurtosis, i tried the
following:
#-----------------------------------------------------------------
kurt <- function(x,weight){
  weight<-weight[!is.na(x)]
  x<-x[!is.na(x)]
  mean.w <- sum(x * weight) / sum(weight)
  sum.w <- sum(weight)
  sum.w2 <- sum(weight^2)
  x.sd.w<-sqrt((sum.w / (sum.w^2 - sum.w2)) * sum(weight * (x - mean.w)^2))
 #((sum(((x - mean.w)/(sd(x)))^4))/(length(x) - 1))         #formula A
 (((sum(((x - mean(x))/(sd(x)))^4))/(length(x) - 1)) - 3)   #formula B
}
kurt(mydata$var,weight)
# weighted Kurtosis is -0.7127631

#-----------------------------------------------------------------
kurtosis<-function(x,weight) {
  weight<-weight[!is.na(x)]
  x<-x[!is.na(x)]
  mean.w <- sum(x * weight) / sum(weight)
  sum.w <- sum(weight)
  sum.w2 <- sum(weight^2)
  x.sd.w<-sqrt((sum.w / (sum.w^2 - sum.w2)) * sum(weight * (x - mean.w)^2))
  m4<-mean((x - mean.w)^4)                                         #formula
C
  kurt<-m4/(x.sd.w^4)-3 
  kurt}
kurtosis(mydata$var,weight)

# weighted Kurtosis is -0.5076363
# unweighted Kurtosis was -0.72
#-----------------------------------------------------------------




--
View this message in context: http://r.789695.n4.nabble.com/Weighted-skewness-and-curtosis-tp4709956p4712612.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list