Hi, I want to perform a ks.test to compare two distributions. I was thinking in using the Kolmogorov-Smirnov test, but the problem is both distributions have to be weighted and they have different lenght. Any idea of how to do it?
Here are my data:
library(tidyverse)
my_data_2018 <- tibble(Var = c(900, 1500, 350, 1200, 750, 100,125,250),
my_weights_2018 = c(2.2, 3.1, 8.2, 4.2, 5.3, 6.8, 12, 25))
my_data_2019 <- tibble(Var = c(32, 21, 21, 900, 1500, 350, 1200, 750, 100,125,250,300),
my_weights_2019 = c(2.2, 3.1, 8.2, 2.2, 3.1, 8.2, 4.2, 5.3, 6.8, 12, 25, 1))
I found this code to create a new ks_weighted function but I am not sure how make it work with my example data
ks_weighted <- function(vector_1,vector_2,weights_1,weights_2){
F_vec_1 <- ewcdf(vector_1, weights = weights_1, normalise=FALSE)
F_vec_2 <- ewcdf(vector_2, weights = weights_2, normalise=FALSE)
xw <- c(vector_1,vector_2)
d <- max(abs(F_vec_1(xw) - F_vec_2(xw)))
## P-VALUE with NORMAL SAMPLE
# n_vector_1 <- length(vector_1)
# n_vector_2<- length(vector_2)
# n <- n_vector_1 * n_vector_2/(n_vector_1 + n_vector_2)
# P-VALUE EFFECTIVE SAMPLE SIZE as suggested by Monahan
n_vector_1 <- sum(weights_1)^2/sum(weights_1^2)
n_vector_2 <- sum(weights_2)^2/sum(weights_2^2)
n <- n_vector_1 * n_vector_2/(n_vector_1 + n_vector_2)
pkstwo <- function(x, tol = 1e-06) {
if (is.numeric(x))
x <- as.double(x)
else stop("argument 'x' must be numeric")
p <- rep(0, length(x))
p[is.na(x)] <- NA
IND <- which(!is.na(x) & (x > 0))
if (length(IND))
p[IND] <- .Call(stats:::C_pKS2, p = x[IND], tol)
p
}
pval <- 1 - pkstwo(sqrt(n) * d)
out <- c(KS_Stat=d, P_value=pval)
return(out)
}
Any idea of how to proceed? Thanks in advance