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

时间:2020-03-05 18:57:40

标签: r dataframe dplyr tidyverse

我试图弄清楚如何将数据帧从长到宽,同时按两个变量(菱形切割以及钻石df的颜色D和F)进行分组,并同时总结数据的一些关键特征。

具体来说,我试图得到95%CI和p值附近的两个均值之间的差异。

Here是我想要的输出表的示例(红色是我要完成的工作)。

下面的示例代码,显示了我已经走了多远:

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.

?

我认为我应该在总结之前的某个时候计算CI和p值表示颜色D和F之间的深度差。

感谢您的输入。

1 个答案:

答案 0 :(得分:1)

要对cut的不同值进行D和F颜色的均值比较(使用t检验),这是您需要做的:

library(broom)

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