【问题标题】:Working with tidyverse, ggplot, and broom to add confidence interval to a proportion test (prop.test) in R使用 tidyverse、ggplot 和 broom 将置信区间添加到 R 中的比例检验 (prop.test)
【发布时间】:2019-12-12 00:04:06
【问题描述】:

假设我正在处理比例,我有两个主要变量(sex 和 pain_level)。绘制它们并不难:

使用 tidyverse 和 broom(感谢此处提供此链接:Calling prop.test function in R with dplyr)我可以比较比例是否在统计上不同。

现在问题来了!

我想在情节中添加错误栏。我知道这并不像我想的那么难,但我找不到办法做到这一点。我试图在此处复制此链接(http://www.andrew.cmu.edu/user/achoulde/94842/labs/lab07_solution.html),但我试图留在 tidyverse 环境中。

所需的输出应该是这样的:

请随意使用下面模拟原始数据集的脚本/语法。

library(tidyverse)
ds <- data.frame(sex = rep(c("M","F"), 18),
                 pain_level = c("High","Moderate","low"))

#plot
ds %>% 
  group_by(pain_level, sex) %>% 
  summarise(n=n()) %>% 
  mutate(prop = n/sum(n)*100) %>% 
  ggplot(., aes(x = sex, fill = pain_level, y = prop)) +
  geom_bar(stat = "summary") +
  facet_wrap( ~ pain_level) +
  theme(legend.position = "none")

#p values of proportion test

ds %>% 
  rowwise %>%
  group_by(pain_level, sex) %>% 
  summarise(cases = n()) %>% 
  mutate(pop = sum(cases)) %>% #compute totals
  distinct(., pain_level, .keep_all= TRUE) %>% #keep only one value of the row 
  mutate(tst = list(broom::tidy(prop.test(cases, pop, conf.level=0.95)))) %>%
  tidyr::unnest(tst)

【问题讨论】:

  • 我无法让您的代码正常运行。 tipo 是一个缺失的变量。通常,geom_errorbar() 可以使用来自prop.tests 的ymin = conf.low 和ymax = conf.high。
  • 对不起,我的错。变量名是 pain_level(而不是 tipo)。您现在可以尝试模仿它吗?我试过 ymin 和 max 但没有成功。谢谢

标签: r ggplot2 tidyverse categorical-data broom


【解决方案1】:

我认为以下内容可能与您想要的输出大致相似:

ds %>% 
  group_by(pain_level, sex) %>% 
  summarise(cases = n()) %>% 
  mutate(pop = sum(cases)) %>%
  rowwise() %>%
  mutate(tst = list(broom::tidy(prop.test(cases, pop, conf.level=0.95)))) %>%
  tidyr::unnest(tst) %>%
  ggplot(aes(sex, estimate, group = pain_level)) +
  geom_col(aes(fill = pain_level)) +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high)) +
  facet_wrap(~ pain_level)

【讨论】:

  • 哇!惊人的。我不知道就这么简单。我总是将“conf.low”和“conf.high”视为我们需要在绘图之前计算的结果。很高兴知道它是由 ggplot 自动计算的。
  • 它们不是由 ggplot 计算的,而是由在将数据交给 ggplot 之前调用的 prop.test() 函数计算的。
  • 啊,好吧!现在我很清楚了!再次感谢,我赞成并接受了您的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-05
  • 2013-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-29
  • 1970-01-01
相关资源
最近更新 更多