Search code examples
rhypothesis-test

How to compare two Probability Density Functions?


I have two Probability Density Functions and I want to know if their distributions are similar or not. I know that KS test in R can do this, but when I run the code, an error occurs. Thanks for any help.

set.seed(100)
a=density(sample(x=1:30,size = 30,replace = T))
b=density(sample(x=1:40,size = 35,replace = T))
plot(a)
lines(b)

ks.test(a,b)
Error in ks.test(a, b) : 
 'y' must be numeric or a function or a string naming a valid function

Solution

  • You need to input the two samples (numeric vectors of data values) as argument of ks.test.

    set.seed(100)
    x <- sample(x=1:30,size = 30,replace = T)
    y <- sample(x=1:40,size = 35,replace = T)
    a=density(x)
    b=density(y)
    plot(a)
    lines(b)
    
    ks.test(x,y)