The Wayback Machine - https://web.archive.org/web/20240820175754/https://www.geeksforgeeks.org/kolmogorov-smirnov-test-in-r-programming/
Open In App

Kolmogorov-Smirnov Test in R Programming

Last Updated : 10 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Kolmogorov-Smirnov Test is a type of non-parametric test of the equality of discontinuous and continuous a 1D probability distribution that is used to compare the sample with the reference probability test (known as one-sample K-S Test) or among two samples (known as two-sample K-S test). A K-S Test quantifies the distance between the cumulative distribution function of the given reference distribution and the empirical distributions of given two samples, or between the empirical distribution of given two samples. In a one-sample K-S test, the distribution that is considered under a null hypothesis can be purely discrete or continuous, or mixed. In the two-sample K-S test, the distribution considered under the null hypothesis is generally continuous distribution but it is unrestricted otherwise. The Kolmogorov-Smirnov test can be done very easily in R Programming Language.

Kolmogorov-Smirnov Test Formula

The formula for the Kolmogorov-Smirnov test can be given as:

D_n=sup_x\left| F_n(x) - F(x)\right|

where,

  • supx : the supremum of the set of distances
  •  Fn(x) : the empirical distribution function for n id observations Xi

The empirical distribution function is a distribution function that is associated with the empirical measures of the chosen sample. Being a step function, this cumulative distribution jumps up by a 1/n step at each and every n data point. 

One Sample Kolmogorov-Smirnov Test in R

The K-S test can be performed using the ks.test() function in R. 

Syntax:

ks.text(x, y, alternative = c(“two.sided”, “less”, “greater”), exact= NULL, tol= 1e-8, 
simulate.p.value = FALSE, B=2000)

Parameters:

  • x: numeric vector of data values
  • y: numeric vector of data values or a character string which is used to name a cumulative distribution function.
  • alternative: used to indicate the alternate hypothesis.
  • exact: usually NULL or it indicates a logic that an exact p-value should be computed.
  • tol: an upper bound used for rounding off errors in the data values.
  • simulate.p.value: a logic that checks whether to use Monte Carlo method to compute the p-value.
  • B: an integer value that indicates the number of replicates to be created while using the Monte Carlo method.

Let us understand how to execute a K-S Test step by step using an example of a two-sample K-S test. First, install the required packages. For performing the K-S test we need to install the “dgof” package using the install.packages() function from the R console.

R

# installing the required package
install.packages("dgof")

                    

After a successful installation of the package, load the required package in our R Script. for that purpose, use the library() function as follows:

R

# loading the required package
library("dgof")

                    

Use the rnorm() function to generate samples say x. The rnorm() function is used to generate random variates.

R

x1 <- rnorm(100)
ks.test(x1, "pnorm")

                    

Output:

    One-sample Kolmogorov-Smirnov test

data:  x1
D = 0.10091, p-value = 0.2603
alternative hypothesis: two-sided

Two Sample Kolmogorov-Smirnov Test in R

Use the rnorm() function and the runif() function to generate samples say x and y. The rnorm() function is used to generate random variates while the runif() function is used to generate random deviates.

R

# generating random variate sample 1
x <- rnorm(50)
 
# generating random deviates sample 2
y <- runif(30)

                    

Now perform the K-S test on these two samples. For that purpose, use the ks.test() of the dgof package.

R

# performing the K-S Test Do x and y
# come from the same distribution?
ks.test(x, y)

                    

Output: 

    Two-sample Kolmogorov-Smirnov test

data:  x and y
D = 0.84, p-value = 5.151e-14
alternative hypothesis: two-sided

Visualization of the Kolmogorov- Smirnov Test in R

Being quite sensitive to the difference in shape and location of the empirical cumulative distribution of the chosen two samples, the two-sample K-S test is efficient, and one of the most general and useful non-parametric tests. Hence we will see how the graph represents the difference between the two samples.

Here we are generating both samples using the rnorm() functions and then plotting them.  

R

# loading the required package
library(dgof)
 
# sample 1
# generating a random variate
x <- rnorm(50)
 
# sample 2
# generating a random variate
x2 <- rnorm(50, -1)
 
# plotting the result
# visualization
plot(ecdf(x),
     xlim = range(c(x, x2)),
     col = "blue")
plot(ecdf(x2),
     add = TRUE,
     lty = "dashed",
     col = "red")
 
# performing the K-S
# Test on x and x2
ks.test(x, x2, alternative = "l")

                    

Output: 

    Two-sample Kolmogorov-Smirnov test

data:  x and x2
D^- = 0.34, p-value = 0.003089
alternative hypothesis: the CDF of x lies below that of y
Visualization of the Kolmogorov- Smirnov Test in R

Visualization of the Kolmogorov- Smirnov Test in R



Previous Article
Next Article

Similar Reads

Kolmogorov-Arnold Network
A Kolmogorov-Arnold Network (KAN) is based on a theorem by Andrey Kolmogorov, further elaborated by Vladimir Arnold, which states that any multivariate continuous function can be represented as a superposition of continuous functions of one variable and addition. This theorem is a foundational result in the theory of neural networks, particularly i
6 min read
Performing Binomial Test in R programming - binom.test() Method
With the help of binom.test() method, we can get the binomial test for some hypothesis of binomial distribution in R Programming. Syntax: binom.test(x, n, p-value) Return: Returns the value of binomial test. Example 1: # Using binom.test() method gfg &lt;- binom.test(58, 100) print(gfg) Output: Exact binomial test data: 58 and 100 number of success
1 min read
Performing F-Test in R programming - var.test() Method
var.test() Method in R Programming language perform the f-test between two normal populations with some hypothesis that variances of two populations are equal in R programming. var.test() Method in R Syntax Syntax: var.test() Return: Returns the F-Test score for some hypothesis. var.test() Method in R Programming language Example Example 1: C/C++ C
1 min read
Differences Between two-sample, t-test and paired t-test
Statistical tests are essential tools in data analysis, helping researchers make inferences about populations based on sample data. Two common tests used to compare the means of different groups are the two-sample t-test and the paired t-test. Both tests are based on the t-distribution, but they have distinct use cases and assumptions. In this arti
7 min read
R - Calculate Test MSE given a trained model from a training set and a test set
Mean Squared Error (MSE) is a widely used metric for evaluating the performance of regression models. It measures the average of the squares of the errors. the average squared difference between the actual and predicted values. The Test MSE, specifically, helps in assessing how well the model generalizes to new, unseen data. In this article, we wil
4 min read
T-Test Approach in R Programming
We will be trying to understand the T-Test in R Programming with the help of an example. Suppose a businessman with two sweet shops in a town wants to check if the average number of sweets sold in a day in both stores is the same or not. So, the businessman takes the average number of sweets sold to 15 random people in the respective shops. He foun
6 min read
One-Proportion Z-Test in R Programming
The One proportion Z-test is used to compare an observed proportion to a theoretical one when there are only two categories. For example, we have a population of mice containing half male and half females (p = 0.5 = 50%). Some of these mice (n = 160) have developed spontaneous cancer, including 95 males and 65 females. We want to know, whether canc
4 min read
Shapiro–Wilk Test in R Programming
The Shapiro-Wilk's test or Shapiro test is a normality test in frequentist statistics. The null hypothesis of Shapiro's test is that the population is distributed normally. It is among the three tests for normality designed for detecting all kinds of departure from normality. If the value of p is equal to or less than 0.05, then the hypothesis of n
4 min read
Two-Proportions Z-Test in R Programming
A two-proportion z-test allows us to compare two proportions to see if they are the same. It calculates the range of values that is likely to include the difference between the population proportions. The z-test is based on a standard normal distribution. It has a critical value i.e. 1.96. for 5% two-tailed. In R, the function used for performing a
6 min read
Fisher’s F-Test in R Programming
Fisher’s F test calculates the ratio between the larger variance and the smaller variance. We use the F test when we want to check whether the means of three or more groups are different or not. F-test is used to assess whether the variances of two populations (A and B) are equal. The method is simple; it consists of taking the ratio between the la
4 min read
Wilcoxon Signed Rank Test in R Programming
The Wilcoxon signed-rank test is a non-parametric statistical hypothesis test used to compare two related samples, matched samples, or repeated measurements on a single sample to estimate whether their population means ranks differ e.g. it is a paired difference test. It can be applied as an alternative to the paired Student's t-test also known as
7 min read
MANOVA Test in R Programming
Multivariate analysis of variance (MANOVA) is simply an ANOVA (Analysis of variance) with several dependent variables. It is a continuation of the ANOVA. In an ANOVA, we test for statistical differences on one continuous dependent variable by an independent grouping variable. The MANOVA continues this analysis by taking multiple continuous dependen
4 min read
Kruskal-Wallis test in R Programming
The Kruskal–Wallis test in R Programming Language is a rank-based test that is similar to the Mann–Whitney U test but can be applied to one-way data with more than two groups. It is a non-parametric alternative to the one-way ANOVA test, which extends the two-samples Wilcoxon test. A group of data samples is independent if they come from unrelated
4 min read
Bartlett’s Test in R Programming
In statistics, Bartlett's test is used to test if k samples are from populations with equal variances. Equal variances across populations are called homoscedasticity or homogeneity of variances. Some statistical tests, for example, the ANOVA test, assume that variances are equal across groups or samples. The Bartlett test can be used to verify that
5 min read
Levene’s Test in R Programming
Levene's test is an inferential statistic used to check if the variances of a variable obtained for two or more groups are equal or not when data comes from a non-normal distribution. Levene’s test is used to check the assumptions that the variances of the populations from different samples drawn are equal or not before running the test like ANOVA.
5 min read
Fligner-Killeen Test in R Programming
The Fligner-Killeen test is a non-parametric test for homogeneity of group variances based on ranks. It is useful when the data are non-normally distributed or when problems related to outliers in the dataset cannot be resolved. It is also one of the many tests for homogeneity of variances which is most robust against departures from normality. The
4 min read
Homogeneity of Variance Test in R Programming
In statistics, a sequence of random variables is homoscedastic if all its random variables have the same finite variance. This is also known as homogeneity of variance. In this article, let's explain methods for checking the homogeneity of variances test in R programming across two or more groups. Some statistical tests, such as two independent sam
7 min read
Mann Whitney U Test in R Programming
A popular nonparametric(distribution-free) test to compare outcomes between two independent groups is the Mann Whitney U test. When comparing two independent samples, when the outcome is not normally distributed and the samples are small, a nonparametric test is appropriate. It is used to see the distribution difference between two independent vari
4 min read
Permutation Hypothesis Test in R Programming
In simple words, the permutation hypothesis test in R is a way of comparing a numerical value of 2 groups. The permutation Hypothesis test is an alternative to: Independent two-sample t-test Mann-Whitney U aka Wilcoxon Rank-Sum Test Let's implement this test in R programming. Why use the Permutation Hypothesis Test? Small Sample Size. Assumptions(f
6 min read
ANOVA (Analysis of Variance) Test in R Programming
ANOVA also known as Analysis of variance is used to investigate relations between categorical variables and continuous variables in the R Programming Language. It is a type of hypothesis testing for population variance. It enables us to assess whether observed variations in means are statistically significant or merely the result of chance by compa
8 min read
Analysis of test data using K-Means Clustering in Python
This article demonstrates an illustration of K-means clustering on a sample random data using open-cv library. Pre-requisites: Numpy, OpenCV, matplot-lib Let's first visualize test data with Multiple Features using matplot-lib tool. # importing required tools import numpy as np from matplotlib import pyplot as plt # creating two test data X = np.ra
2 min read
Upper Tail Test of Population Mean with Unknown Variance in R
A statistical hypothesis test is a method of statistical inference used to decide whether the data at hand sufficiently support a particular hypothesis. The conventional steps that are followed while formulating the hypothesis test, are listed as follows State null hypothesis (Ho) and alternate hypothesis (Ha)Collect a relevant sample of data to te
3 min read
Python | Create Test DataSets using Sklearn
Python's Sklearn library provides a great sample dataset generator which will help you to create your own custom dataset. It's fast and very easy to use. Following are the types of samples it provides.For all the above methods you need to import sklearn.datasets.samples_generator. C/C++ Code # importing libraries from sklearn.datasets import make_b
3 min read
Levene's test
In this article, we will learn about Levene's test which is generally used to assess the equality of variances between two or more groups or samples. What is Levene Test? Levene's test is used to assess the equality of variance between two different samples. For every case, it calculates the absolute difference between the value of that case and it
4 min read
Generate Test Datasets for Machine learning
Whenever we think of Machine Learning, the first thing that comes to our mind is a dataset. While there are many datasets that you can find on websites such as Kaggle, sometimes it is useful to extract data on your own and generate your own dataset. Generating your own dataset gives you more control over the data and allows you to train your machin
3 min read
How to split a Dataset into Train and Test Sets using Python
Here we will discuss how to split a dataset into Train and Test sets in Python. The train-test split is used to estimate the performance of machine learning algorithms that are applicable for prediction-based Algorithms/Applications. This method is a fast and easy procedure to perform such that we can compare our own machine learning model results
3 min read
Lower Tail Test of Population Mean with Unknown Variance in R
This article will discuss the lower Two-Tailed Test of Population Mean with Unknown Variance in R Programming Language. Conventionally, In a lower tail test is used in null-hypothesis testing. The lower tail test of the population means the null hypothesis can be expressed as follows μ ≥ μo. A statistical hypothesis test is a method of statistical
3 min read
Runs Test of Randomness in Python
Random numbers are an imperative part of many systems, including simulations, cryptography and much more. So the ability to produce values randomly, with no apparent logic and predictability, becomes a prime function. Since computers cannot produce values which are completely random, algorithms, known as pseudorandom number generators (PRNG) are us
4 min read
Kruskal Wallis Test
Kruskal Wallis Test: It is a nonparametric test. It is sometimes referred to as One-Way ANOVA on ranks. It is a nonparametric alternative to One-Way ANOVA. It is an extension of the Man-Whitney Test to situations where more than two levels/populations are involved. This test falls under the family of Rank Sum tests. It depends on the ranks of the s
4 min read
Mann and Whitney U test
Mann and Whitney's U-test or Wilcoxon rank-sum test is the non-parametric statistic hypothesis test that is used to analyze the difference between two independent samples of ordinal data. In this test, we have provided two randomly drawn samples and we have to verify whether these two samples is from the same population. The assumption for Mann-Whi
4 min read
three90RightbarBannerImg