ggplot 中的中位数统计差异

Median statistical difference in ggplot

我有一个像这样的 ggplot 箱线图:

library(ggplot2)
data(iris)
ggplot(iris, aes(x = "", y = Sepal.Width)) +
    geom_boxplot()

如你所见,中位数是3。假设真实值为3.8,我想知道真实值3.8和观察值3之间是否存在统计差异,那么应该采用什么统计差异方法我用?我可以在 R 中实现它吗?也可以在图中绘制 3.8 的实际值吗?

谢谢!

PS:我使用 iris 数据集作为我的真实数据的一个易于重现的例子。

您正在寻找单样本 Wilcoxon 符号秩检验:

wilcox.test(iris$Sepal.Width, mu = 3.8)
#> 
#>  Wilcoxon signed rank test with continuity correction
#> 
#> data:  iris$Sepal.Width
#> V = 113, p-value < 2.2e-16
#> alternative hypothesis: true location is not equal to 3.8

您可以使用 geom_hline 向箱线图添加水平线,使用 geom_text

添加文本注释
ggplot(iris, aes(x = "", y = Sepal.Width)) +
  geom_boxplot() + 
  geom_hline(aes(yintercept=3.8), linetype = 2) +
  geom_text(aes(label = "True median", x = 0.5, y = 3.9))

另一个可行的选择是 bootstrapping。

当你 bootstrap 时,你从你的原始样本中抽取了许多随机样本并进行了替换(这意味着你的样本中的单个观察结果可能会在你的某些 bootstrap 样本中出现不止一次),然后使用 bootstrap 个样本来估计您感兴趣的统计数据。 bootstrap 的妙处在于,您可以使用它来估计几乎所有感兴趣的统计数据的置信区间,无论是均值、中位数、相关性、混合效应回归模型中的斜率等...

要使用 tidyverse 在 R 中实现它,您可以执行以下操作:

# Write a function to get your statistic of interest on a randomly drawn sample
# (i.e. median in your case) with replacement

get_median <- function(x) {

   x_sample <- sample(x, size = length(x), replace = TRUE)
   median(x)

}  

# After that you iterate your function many times (e.g. 1000 times) using purrr

bootstrapped_medians <- purrr::map_dbl(1:1000, ~ get_medians(x = iris$Sepal.Width))

# Now you can use the vector of bootstrapped statistics to get the desired summary
# e.g. 95% confidence interval

quantile(bootstrapped_medians, c(0.025, 0.975))