Wednesday, September 25, 2024

BCA PART B 5.R program to calculate arithmetic mean for grouped and ungrouped data

  1. Ungrouped Data (mean_ungrouped):

    • The mean_ungrouped function computes the mean of a vector of data using the mean() function, which calculates the sum of all values divided by the number of values.
  2. Grouped Data (mean_grouped):

    • For grouped data, we first calculate the midpoints of each class interval using the formula: midpoint=lower bound+upper bound2\text{midpoint} = \frac{\text{lower bound} + \text{upper bound}}{2}
    • Then, we compute the arithmetic mean using the frequency-weighted mean formula: Mean=(midpoint×frequency)frequency\text{Mean} = \frac{\sum (\text{midpoint} \times \text{frequency})}{\sum \text{frequency}}

Program:

# Function to calculate arithmetic mean for ungrouped data
mean_ungrouped <- function(data) {
  mean_val <- mean(data)
  return(mean_val)
}

# Function to calculate arithmetic mean for grouped data
mean_grouped <- function(lower_bound, upper_bound, frequency) {
  # Calculate midpoints of the class intervals
  midpoints <- (lower_bound + upper_bound) / 2
 
  # Calculate the weighted mean for the grouped data
  mean_val <- sum(midpoints * frequency) / sum(frequency)
 
  return(mean_val)
}

# Example Usage for Ungrouped Data
ungrouped_data <- c(10, 20, 30, 40, 50)  # Example ungrouped data
cat("Arithmetic Mean for Ungrouped Data:\n")
print(mean_ungrouped(ungrouped_data))

# Example Usage for Grouped Data
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
cat("\nArithmetic Mean for Grouped Data:\n")
print(mean_grouped(lower_bound, upper_bound, frequency))

Output:

Arithmetic Mean for Ungrouped Data:

[1] 30


Arithmetic Mean for Grouped Data:

[1] 20



No comments:

Post a Comment