[英]Kolmogorov-Smirnov test and weighted data
我想執行 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 function 但我不確定如何使它與我的示例數據一起使用
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)
}
您可以使用 FastDR 中的ks
function 獲得加權 Kolmogorov-Smirnov 統計量,然后計算兩側檢驗的 p 值。
FastDR 由賓夕法尼亞大學教授 Greg Ridgeway 編寫。 我認為該方法將是可靠的。
首先,從 GitHub 獲取 package。
if(!require(devtools)) install.packages("devtools")
library(devtools)
install_github("gregridgeway/survey","patch-1")
install_github("gbm-developers/gbm3")
install_github("gregridgeway/fastDR")
要根據您的數據計算 KS 測試統計數據,您可以使用以下代碼:
library(fastDR)
Var <- c(my_data_2018$Var,my_data_2019$Var)
weights <- c(my_data_2018$my_weights_2018,my_data_2019$my_weights_2019)
treat <- c(rep(0,nrow(my_data_2018)),rep(1,nrow(my_data_2019)))
ks.test.stats <- ks(x=Var,z=treat,w=weights)
您將獲得以下 KS 測試統計信息:
## KS Test Statistics
ks.test.stats
[1] 0.1660517
最后,要計算雙面測試的 p 值,您可以使用以下代碼:
### "Two-Sided" P-Value for KS Tests Statistics from R
p.value <- 1-.Call(stats:::C_pSmirnov2x,
STAT=ks.test.stats,
length(my_data_2018$Var),
length(my_data_2019$Var))
p.value
> ks.test.stats
[1] 0.1660517
注意:如果您在下載 package 時遇到問題,請嘗試更改您的 R 版本。 看來 FastDR 的依賴性不適用於 R 版本 4.00。 我使用 R 版本 3.63 進行此計算。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.