Wednesday, September 25, 2024

BCA PART B 3.R program to calculate coefficient of variance for discrete & continuous series

 Coefficient of Variation (CV) is defined as the ratio of the standard deviation (σ) to the mean (μ) and is usually expressed as a percentage:

CV=(σμ)×100CV = \left(\frac{\sigma}{\mu}\right) \times 100

Program :

# Function to calculate Coefficient of Variation for a Discrete Series
cv_discrete <- function(x) {
  mean_val <- mean(x)
  sd_val <- sd(x)
 
  cv <- (sd_val / mean_val) * 100
  return(cv)
}

# Function to calculate Coefficient of Variation for a Continuous Series
cv_continuous <- function(lower_bound, upper_bound, frequency) {
  # Calculate midpoints of the class intervals
  midpoints <- (lower_bound + upper_bound) / 2
 
  # Calculate the mean for the continuous series
  mean_val <- sum(midpoints * frequency) / sum(frequency)
 
  # Calculate variance
  variance <- sum(frequency * (midpoints - mean_val)^2) / sum(frequency)
 
  # Calculate standard deviation
  sd_val <- sqrt(variance)
 
  # Calculate Coefficient of Variation
  cv <- (sd_val / mean_val) * 100
  return(cv)
}

# Example Usage for Discrete Series:
discrete_data <- c(10, 20, 30, 40, 50)  # Example values for discrete series
cv_discrete(discrete_data)

# Example Usage for Continuous Series:
lower_bound <- c(0, 10, 20, 30)  # Lower bounds of class intervals
upper_bound <- c(10, 20, 30, 40) # Upper bounds of class intervals
frequency <- c(5, 10, 8, 7)      # Frequency of each class interval
cv_continuous(lower_bound, upper_bound, frequency)

Output :

52.704627669473
49.4769730650902

Explanation:

  • Discrete Series:
    • cv_discrete: This function takes a vector x of discrete values and computes the coefficient of variation using the mean and sd (standard deviation) functions in R.
  • Continuous Series:
    • cv_continuous: This function takes three inputs:
      • lower_bound: A vector of the lower bounds of class intervals.
      • upper_bound: A vector of the upper bounds of class intervals.
      • frequency: A vector of frequencies for each class interval.
    • It calculates the midpoint of each class interval, then computes the mean and standard deviation of the data and finally calculates the coefficient of variation.



No comments:

Post a Comment