Function to generate and test data

# Define a function named generate_and_test that takes three parameters:
#   - sample_size: the size of each sample
#   - mean_difference: the mean difference between two groups
#   - standard_deviation: the standard deviation for both groups
generate_and_test <- function(sample_size, mean_difference, standard_deviation) {
  
  # Generate a random sample for group1 from a normal distribution with mean 0 and the given standard deviation
  group1 <- rnorm(sample_size, mean = 0, sd = standard_deviation)
  
  # Generate a random sample for group2 from a normal distribution with mean equal to mean_difference
  # and the given standard deviation
  group2 <- rnorm(sample_size, mean = mean_difference, sd = standard_deviation)
  
  # Perform a t-test to compare the means of group1 and group2
  t_test_result <- t.test(group1, group2)
  
  # Calculate the pooled standard deviation, which is used in the calculation of Cohen's d
  # Pooled SD is a way to combine the standard deviations of two groups into a single value
  pooled_sd <- sqrt(((length(group1) - 1) * sd(group1)^2 + (length(group2) - 1) * sd(group2)^2) / (length(group1) + length(group2) - 2))
  
  # Calculate Cohen's d, which is a measure of effect size that represents the standardized difference between two means
  cohen_d <- mean(group1) - mean(group2) / pooled_sd
  
  # Return a list containing the effect size (Cohen's d) and the p-value from the t-test
  return(list(
    effect_size = cohen_d,
    p_value = t_test_result$p.value
  ))
}

Model p values

# Initialize
results_list <- list()
sample_sizes <- c(3, 6, 12)
mean_differences <- c(1, 2, 3)
standard_deviations <- seq(0.5, 2, by = 0.5)

# Loop through combinations of parameters
for (size in sample_sizes) {
  for (difference in mean_differences) {
    for (std_dev in standard_deviations) {
      result <- generate_and_test(size, difference, std_dev)
      results_list <- append(results_list, list(list(
        sample_size = size,
        mean_difference = difference,
        standard_deviation = std_dev,
        effect_size = result$effect_size,
        p_value = result$p_value
      )))
    }
  }
}

results_df <- do.call(rbind.data.frame, results_list)



# Explanation:

# 1. Initialization (Line 50):
# The code initializes an empty list, results_list, to store the results of the statistical analysis.

# 2. Parameter Definition (Lines 51-54):
# Three vectors, sample_sizes, mean_differences, and standard_deviations, are defined to represent
# the possible values for sample sizes, mean differences, and standard deviations. These vectors define
# the range of values to explore in the statistical analysis.

# 3. Nested Looping (Lines 56-70):
# Three nested loops iterate through all combinations of sample sizes, mean differences, and standard deviations.
# This exhaustive approach ensures that the statistical analysis is performed for each unique combination of parameters.

# 4. Function Call (Line 60):
# Inside the nested loops, the generate_and_test function is called with the current combination of parameters.
# This function generates random samples, performs a t-test, and calculates effect size.

# 5. Results Storage (Lines 62-66):
# The results, including sample size, mean difference, standard deviation, effect size, and p-value, are appended as a list to the results_list. This creates a structured storage of results for later analysis.

# 6. Data Frame Creation (Line 72):
# Finally, the list of results is combined into a data frame, results_df, using do.call(rbind.data.frame, results_list).

# This step organizes the results into a tabular format for easier interpretation and further analysis.

# In summary, this code systematically explores various combinations of sample sizes, mean differences, and standard deviations, conducting statistical tests for each combination and organizing the results into a structured data frame. This approach is useful for understanding how different parameters impact statistical outcomes.

Calculate observed power

calculate_observed_power <- function(effect_size, sample_size, standard_deviation, alpha = 0.05) {
  # Calculate observed power using power.t.test
  power_result <- power.t.test(n = sample_size, delta = effect_size, sig.level = alpha, type = "two.sample")
  observed_power <- power_result$power
  return(observed_power)
}

# Calculate observed power for each combination of parameters
results_df$observed_power <- mapply(calculate_observed_power, 
                                     results_df$effect_size, 
                                     results_df$sample_size)

# Explanation:

# Function Explanation (Lines 108-112):
# The calculate_observed_power function takes effect_size, sample_size, standard_deviation, and alpha as parameters.
# It uses the power.t.test function to calculate the observed power based on a two-sample t-test.
# The result is extracted from the power_result and returned as observed_power.

# Results Calculation (Lines 114-116):
# The mapply function is used to apply the calculate_observed_power function to each combination of effect_size and sample_size
# in the results_df data frame. The calculated observed power values are then added as a new column, observed_power, in the data frame.

# In summary, this code defines a function to calculate observed power for a two-sample t-test based on given parameters.
# It then applies this function to each combination of effect size and sample size in the results_df data frame, adding the
# calculated observed power values to the data frame for further analysis.

Plot p-value vs. effect size for each sample size

library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.2.3
ggplot(results_df, aes(x = effect_size, y = p_value, color = as.factor(sample_size))) +
  geom_point() +
  geom_hline(yintercept = 0.05, linetype = "dashed") +
  labs(title = "P-value vs. Effect Size",
       x = "Effect Size",
       y = "P-value",
       color = "Sample Size") +
  theme_minimal()

Plot observed power vs. effect size for each sample size

ggplot(results_df, aes(x = effect_size, y = observed_power, color = as.factor(sample_size))) +
  geom_point() +
  labs(title = "Observed Power vs. Effect Size",
       x = "Effect Size",
       y = "Observed Power",
       color = "Sample Size") +
  theme_minimal()