【发布时间】:2020-10-12 06:51:47
【问题描述】:
我想执行 ks.test 来比较两个分布。我在考虑使用 Kolmogorov-Smirnov 检验,但问题是两个分布都必须加权。知道怎么做吗?
这是我的数据:
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))
我找到了这段代码来创建一个新的 ks_weighted 函数,但我不确定如何使它与我的示例数据一起工作
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)
}
【问题讨论】:
标签: r