Wednesday, 12 April 2023

R function ci_sigma

The function ci_sigma evaluates the  confidence interval of variance and standard deviation  for populations that are approximately normal. ci_sigma takes two arguments:

  • x: a vector of data.
  • alpha: significance level (default = 0.05).

The function checks if the input data is approximately normal using the Shapiro-Francia test from the nortest package. If the hypothesis of normality is not satisfied at the given significance level, it suggests trying a log-transformation and performs the Shapiro-Francia test again. If the hypothesis of normality is satisfied, it calculates critical values from the chi-squared distribution and uses them to calculate confidence intervals for both variance and standard deviation.

The function returns a list containing five elements:

  • VAR: variance of input data.
  • SD: standard deviation of input data.
  • CI.VAR: confidence interval for variance.
  • CI.SD: confidence interval for standard deviation.
  • dof: degrees of freedom.

Here is an example usage of this function:

x <- rnorm(100, mean = 10, sd = 2)

ci_sigma(x)


#CONFIDENCE INTERVAL OF STANDARD DEVIATION

#For populations that are approximately normal

ci_sigma<- function(x,alpha=0.05) {

  #x:          vector of data

  #alpha:      significance level (default=0.05)

 

  n<- length(x)

 

  #check normality

  library(nortest)

  out<-sf.test(x)

  out

 

  if(out$p.value<alpha) {

    print("the hypothesis of normality is not satisfied. Try log-trasformation")

    sf.test(log(x))

  } else {

    #critical values from the chi-squared distribution

    u.low<- qchisq(alpha/2,n-1,lower.tail=FALSE)

    u.up<- qchisq(1-alpha/2,n-1,lower.tail=FALSE)

   

    ci.var.low<- (n-1)*var(x)/u.low

    ci.var.up<- (n-1)*var(x)/u.up

   

    ci.var<- c(ci.var.low,ci.var.up)

    ci.std<- sqrt(ci.var)

   

    return(list(VAR=var(x),SD=sd(x),CI.VAR=ci.var,CI.SD=ci.std,dof=n-1))

  }

}

 


No comments:

Post a Comment

Understanding Anaerobic Threshold (VT2) and VO2 Max in Endurance Training

  Introduction: The Science Behind Ventilatory Thresholds Every endurance athlete, whether a long-distance runner, cyclist, or swimmer, st...