简体   繁体   English

具有汇总函数和 tidyverse 的均值之间差异的置信区间和 p 值

[英]Confidence interval and p.values for difference between means with summarize function and tidyverse

I am trying to figure out how to turn a data frame from long to wide, while grouping by two variables (diamond cut and colors D and F from diamonds df) and summarizing some key features of the data at the same time.我试图弄清楚如何将数据框从长到宽,同时按两个变量(钻石切割和颜色 D 和 F 来自钻石 df)分组并同时总结数据的一些关键特征。

Specifically, I am trying to get the difference between two means, 95% CI and p-values around that difference.具体来说,我试图获得两个平均值之间的差异,即 95% CI 和围绕该差异的 p 值。

Here is an example of my desired output table (in red is what I am trying to accomplish). 是我想要的输出表的一个例子(红色是我想要完成的)。

Sample code below, showing how far I've gotten:下面的示例代码,显示了我已经走了多远:

library(tidyverse)

# Build summary data

diamonds <- diamonds %>% 
  select(cut, depth, color) %>% 
  filter(color == "F" | color == "D") %>% 
  group_by(cut, color) %>% 
  summarise(mean = mean(depth), #calculate mean & CIs
            lower_ci = mean(depth) - qt(1- 0.05/2, (n() - 1))*sd(depth)/sqrt(n()),
            upper_ci = mean(depth) + qt(1- 0.05/2, (n() - 1))*sd(depth)/sqrt(n()))

# Turn table from long to wide

diamonds <- dcast(as.data.table(diamonds), cut ~ color, value.var = c("mean", "lower_ci", "upper_ci"))

# Rename & calculate the mean difference

diamonds <- diamonds %>%
  rename(
    Cut = cut,
    Mean.Depth.D = mean_D,
    Mean.Depth.F = mean_F,
    Lower.CI.Depth.D = lower_ci_D,
    Lower.CI.Depth.F = lower_ci_F,
    Upper.CI.Depth.D = upper_ci_D,
    Upper.CI.Depth.F = upper_ci_F) %>% 
  mutate(Mean.Difference = Mean.Depth.D - Mean.Depth.F)

# Re-organize the table

diamonds <- subset(diamonds, select = c(Cut:Mean.Depth.F, Mean.Difference, Lower.CI.Depth.D:Upper.CI.Depth.F))

#Calculate the CIs (upper and lower) and p.values for mean difference for each cut and insert them into the table.

?

I think I am supposed to calculate the CIs and p-values mean difference in depth between colors D and F at some point before I summarize, but not exactly sure how.我想我应该在我总结之前的某个时间计算 CI 和 p 值平均颜色 D 和 F 之间的深度差异,但不完全确定如何。

Thanks for the input.感谢您的投入。

To get comparisons of means (with t-tests) for D and F colours across different values for cut , this is what you would need to do:要在cut不同值之间比较 D 和 F 颜色的均值(使用 t 检验),您需要执行以下操作:

library(broom)

diamonds %>% 
   filter(color %in% c("D", "F")) %>% 
   group_by(cut) %>% 
   do( tidy(t.test(data=., depth~color)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM