Write a R program for Z test

1. Introduction

This R program performs a Z test, which is a statistical test used to determine whether two population means are different when the variances are known and the sample size is large. The Z test is often used for hypothesis testing in statistics.

2. Program Steps

1. Define sample data and known population parameters.

2. Calculate the Z score using the formula: \( Z = \frac{(\bar{x} - \mu)}{(\sigma / \sqrt{n})} \).

3. Compare the Z score with the standard normal distribution to determine the p-value.

4. Print the Z score and the p-value.

3. Code Program

# Step 1: Define sample data and population parameters
sample_data <- c(101, 100, 102, 104, 102, 97, 105, 105, 98, 94)  # Sample data
mu <- 100  # Known population mean
sigma <- 5  # Known population standard deviation
n <- length(sample_data)  # Sample size

# Step 2: Calculate the Z score
x_bar <- mean(sample_data)  # Sample mean
z_score <- (x_bar - mu) / (sigma / sqrt(n))

# Step 3: Determine the p-value
p_value <- 2 * pnorm(-abs(z_score))  # Two-tailed test

# Step 4: Print the Z score and p-value
print("Z score:")
print(z_score)
print("P-value:")
print(p_value)

Output:

Z score:
[Calculated Z Score]
P-value:
[Calculated P-value]

Explanation:

1. sample_data <- c(...): Defines a vector representing the sample data.

2. mu <- 100, sigma <- 5, n <- length(sample_data): Sets the known population mean, standard deviation, and calculates the sample size.

3. z_score <- (x_bar - mu) / (sigma / sqrt(n)): Calculates the Z score using the Z test formula.

4. p_value <- 2 * pnorm(-abs(z_score)): Calculates the p-value for a two-tailed test based on the Z score.

5. print("Z score:"), print(z_score): Prints the calculated Z score.

6. print("P-value:"), print(p_value): Prints the calculated p-value, which indicates the probability of observing such an extreme value by chance if the null hypothesis is true.


Comments