How to perform One Sample & Two Sample Z-Tests in R

How to Easily Perform One and Two Sample Z-Tests in R

The Z-test is a fundamental statistical tool used to determine if a specific population parameter, such as the mean, is significantly different from a hypothesized value or if two population means are significantly different from each other. While basic calculations for the Z-score and associated probabilities can be manually executed in the R programming language using built-in functions like qnorm() (to find quantiles) or pnorm() (to find cumulative probabilities), performing a full hypothesis test requires several steps.

For more streamlined and robust hypothesis testing, researchers often rely on specialized statistical packages. Although one might attempt to adapt the general t.test() function by providing necessary arguments, this method is often cumbersome and error-prone when dealing specifically with Z-distributions where the population standard deviation is known. This guide will focus on the most direct and conventional method for executing both one-sample and two-sample Z-tests within R, utilizing a dedicated package designed for this precise task.


Accessing the Z-Test Functionality in R

To execute both one-sample and two-sample Z-tests efficiently within R, the ideal approach is to leverage the specialized function z.test(). This powerful function is housed within the BSDA package (Basic Statistical Data Analysis). Using a dedicated package simplifies the workflow, ensures proper calculation of the test statistic, and provides a clean output summary that includes the calculated Z-score, the p-value, and the confidence interval.

Before proceeding with any examples, you must ensure that the BSDA package is installed and loaded into your R session. This package provides the necessary computational infrastructure for tests where the population variances or standard deviations are known, a key requirement for using the Z-test over the T-test.

Understanding the z.test() Function Syntax

The z.test() function is highly flexible, designed to handle both single-sample scenarios (comparing a sample mean to a known population mean) and two-sample scenarios (comparing two independent sample means). Mastering its core syntax is essential for accurate execution of the test. Below is the fundamental structure of the function call, followed by a detailed explanation of its essential parameters.

z.test(x, y, alternative='two.sided', mu=0, sigma.x=NULL, sigma.y=NULL,conf.level=.95)

where:

  • x: This required argument represents the vector of data containing the observations for the first sample. For a one-sample test, this is the only sample data needed.
  • y: This optional vector contains the observations for the second sample. It should only be included when performing a two-sample Z-test to compare the means of two distinct groups.
  • alternative: Specifies the nature of the alternative hypothesis. Options include ‘two.sided’ (the default, testing for difference in either direction), ‘greater’ (testing if the mean is larger than the hypothesized value), or ‘less’ (testing if the mean is smaller).
  • mu: This parameter defines the value specified by the null hypothesis. In a one-sample test, it is the hypothesized population mean (μ₀). In a two-sample test, it represents the hypothesized difference between the population means, usually set to 0, assuming no difference.
  • sigma.x: This is the critical input for Z-tests: the known population standard deviation (σₓ) for the first sample group. This parameter must be provided; otherwise, the function will default to a T-test approach if sample sizes are large.
  • sigma.y: If a two-sample test is being conducted, this parameter specifies the known population standard deviation (σᵧ) for the second sample group.
  • conf.level: Determines the desired confidence level for the interval estimation, typically set to 0.95 (or 95%).

The following detailed examples illustrate how to implement this powerful function in practice, demonstrating scenarios for both one-sample and two-sample comparisons.

Example 1: Performing a One-Sample Z-Test in R

A one-sample Z-test is employed when we want to test whether the mean of a single sample differs significantly from a known or hypothesized population mean, under the critical condition that the population standard deviation (σ) is established. Consider a scenario involving IQ testing, where it is known that the global population of IQ scores is normally distributed with a mean (μ) of 100 and a population standard deviation (σ) of 15.

A clinical researcher is investigating the potential impact of a novel cognitive-enhancing medication. The researcher hypothesizes that this medication might alter general IQ levels. To test this, a random sample of 20 patients is recruited to take the medication for a defined period, after which their IQ scores are measured. The goal is to determine if the mean IQ of this treated sample deviates significantly from the established population mean of 100.

We formulate our hypotheses: the null hypothesis (H₀) states that the medication has no effect (sample mean equals 100), and the alternative hypothesis (H₁) states that the mean is not equal to 100. The R code below demonstrates the practical application of the z.test() function to address this two-sided test.

library(BSDA)

#enter IQ levels for 20 patients
data = c(88, 92, 94, 94, 96, 97, 97, 97, 99, 99,
         105, 109, 109, 109, 110, 112, 112, 113, 114, 115)

#perform one sample z-test
z.test(data, mu=100, sigma.x=15)

	One-sample z-Test

data:  data
z = 0.90933, p-value = 0.3632
alternative hypothesis: true mean is not equal to 100
95 percent confidence interval:
  96.47608 109.62392
sample estimates:
mean of x 
   103.05 

Upon reviewing the output from the z.test() function, several critical results are presented. The calculated test statistic (z) is 0.90933, and the corresponding p-value is 0.3632. The sample mean for the treated group was calculated to be 103.05, which is slightly higher than the population mean of 100.

To make a statistical decision, we compare the p-value against a predetermined significance level (alpha, typically α = 0.05). Since 0.3632 is significantly greater than 0.05, we fail to obtain sufficient statistical evidence to reject the null hypothesis. This indicates that the observed difference between the sample mean (103.05) and the hypothesized population mean (100) is likely due to random sampling variation, rather than a true effect of the medication.

In conclusion, based on the results of the one-sample Z-test, we must conclude that the new medication, based on this specific sample data, does not appear to cause a statistically significant alteration in the mean IQ level of the patients. The 95% confidence interval (96.47608 to 109.62392) also strongly supports this finding, as it comfortably contains the hypothesized population mean of 100.

Example 2: Executing a Two-Sample Z-Test for Mean Comparison

A two-sample Z-test is used to determine if there is a statistically significant difference between the means of two independent populations. This test, like its one-sample counterpart, requires that we know the population standard deviation for both groups. Imagine a study comparing the average IQ levels of residents in two distinct geographical areas, City A and City B. Historical data suggests that IQ scores in both populations are normally distributed, and critically, the population standard deviation for both groups is known to be σ = 15.

The researcher’s objective is to ascertain whether the average intellectual performance, represented by the mean IQ score, differs between the residents of City A and City B. To investigate this, a simple random sample of 20 individuals is drawn from City A and an independent random sample of 20 individuals is drawn from City B. The measurements collected form the data vectors cityA and cityB. Our formal null hypothesis (H₀) asserts that there is no difference in the true mean IQ between the two cities (μ₁ – μ₂ = 0).

The implementation of the two-sample z.test() requires specifying both data vectors (x and y) and their respective known population standard deviations (sigma.x and sigma.y). Since we are testing for any difference, we default to the two-sided alternative hypothesis, and set the hypothesized mean difference (mu) to zero.

library(BSDA)

#enter IQ levels for 20 individuals from each city
cityA = c(82, 84, 85, 89, 91, 91, 92, 94, 99, 99,
         105, 109, 109, 109, 110, 112, 112, 113, 114, 114)

cityB = c(90, 91, 91, 91, 95, 95, 99, 99, 108, 109,
         109, 114, 115, 116, 117, 117, 128, 129, 130, 133)

#perform two sample z-test
z.test(x=cityA, y=cityB, mu=0, sigma.x=15, sigma.y=15)

	Two-sample z-Test

data:  cityA and cityB
z = -1.7182, p-value = 0.08577
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -17.446925   1.146925
sample estimates:
mean of x mean of y 
   100.65    108.80

The R output provides the results of the two-sample comparison. The calculated Z-test statistic is -1.7182, and the resulting p-value is 0.08577. The sample means show that City A had an average IQ of 100.65, while City B had a higher average IQ of 108.80, leading to an observed mean difference of -8.15.

Following the standard procedure, we compare the p-value (0.08577) to the significance level (α = 0.05). Since the p-value is greater than the threshold (0.08577 > 0.05), we must again fail to reject the null hypothesis. While there is an observable difference in the sample means, this difference is not large enough, relative to the known population standard deviations and sample sizes, to be considered statistically significant at the 95% confidence level.

Therefore, our statistical conclusion is that there is insufficient evidence to claim that the true mean IQ levels of the populations in City A and City B are significantly different. The confidence interval for the true difference in means, which ranges from -17.45 to 1.15, includes zero, which further reinforces our decision not to reject the null hypothesis.

Summary and Further Statistical Analysis in R

The z.test() function provided by the BSDA package offers an efficient and reliable method for conducting both one-sample and two-sample Z-tests within the R programming language. It is crucial to remember that the validity of the Z-test hinges entirely on the assumption that the population standard deviation (σ) is known. When σ is unknown—which is frequently the case in real-world data analysis—the Z-test is inappropriate, and a T-test must be utilized instead, relying on the sample standard deviation to estimate variability.

Understanding the distinction between these tests is vital for accurate statistical reporting. The decision to reject or fail to reject the null hypothesis depends on comparing the calculated p-value to the selected significance level. A statistically significant result indicates that the observed data is unlikely to have occurred if the null hypothesis were true.

For those looking to expand their statistical toolkit, the R environment offers numerous packages and functions for other common inferential statistics. Exploring these tutorials will provide insight into situations where assumptions preclude the use of the Z-test, such as when dealing with small samples or unknown population variance.

The following tutorials explain how to perform other common statistical tests in R:

Cite this article

stats writer (2025). How to Easily Perform One and Two Sample Z-Tests in R. PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/how-to-perform-one-sample-two-sample-z-tests-in-r/

stats writer. "How to Easily Perform One and Two Sample Z-Tests in R." PSYCHOLOGICAL SCALES, 3 Dec. 2025, https://scales.arabpsychology.com/stats/how-to-perform-one-sample-two-sample-z-tests-in-r/.

stats writer. "How to Easily Perform One and Two Sample Z-Tests in R." PSYCHOLOGICAL SCALES, 2025. https://scales.arabpsychology.com/stats/how-to-perform-one-sample-two-sample-z-tests-in-r/.

stats writer (2025) 'How to Easily Perform One and Two Sample Z-Tests in R', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/how-to-perform-one-sample-two-sample-z-tests-in-r/.

[1] stats writer, "How to Easily Perform One and Two Sample Z-Tests in R," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, December, 2025.

stats writer. How to Easily Perform One and Two Sample Z-Tests in R. PSYCHOLOGICAL SCALES. 2025;vol(issue):pages.

Download Post (.PDF)

Comments are closed.

Slide Up
x
PDF
Scroll to Top