假设检验:独立样本检验

knitr::opts_chunk$set(echo = TRUE)

安装包

library(dplyr)
library(ggplot2)

加载数据

# Data in two numeric vectors
women_weight <- c(38.9, 61.2, 73.3, 21.8, 63.4, 64.6, 48.4, 48.8, 48.5)
men_weight <- c(67.8, 60, 63.4, 76, 89.4, 73.3, 67.3, 61.3, 62.4) 
# Create a data frame
my_data <- data.frame( 
                group = rep(c("Woman", "Man"), each = 9),
                weight = c(women_weight,  men_weight)
                )
head(my_data)

初步了解数据 EDA

男女两组数据的基本情况

# Compute summary statistics by groups
my_data %>% 
  group_by(group) %>%
  summarise(
    count = n(),
    mean = mean(weight, na.rm = TRUE),
    sd = sd(weight, na.rm = TRUE)
  )

可视化一下

# Plot weight by group and color by group
ggplot(my_data, aes(group,weight)) +
  geom_boxplot(aes(fill = group))

带着问题去分析

男女平均体重是否有显著差异?

参数方法

假设条件的验证

  1. 独立?

由于男女样本不相关,所以两样本是独立的。

  1. 正态分布?
# Shapiro-Wilk normality test for Men's weights
with(my_data, shapiro.test(weight[group == "Man"]))# p = 0.1

my_data %>% 
  filter(group == "Man") %>% 
  select(weight) %>% 
  unlist %>% 
    shapiro.test()
                 
# Shapiro-Wilk normality test for Women's weights
with(my_data, shapiro.test(weight[group == "Woman"])) # p = 0.6

可视化一下

ggplot(my_data %>% filter(group=="Man"), aes(sample=weight))+
  geom_qq() +
  geom_qq_line()
  1. 样本符合方差齐性吗?

使用F检验

res.ftest <- var.test(weight ~ group, data = my_data)
res.ftest

计算两组独立数据的t检验

# Compute t-test - method1
res <- t.test(women_weight, men_weight, var.equal = TRUE)
res

# Compute t-test - method2
res <- t.test(weight ~ group, data = my_data, var.equal = TRUE)
res

解释一下结果:

# printing the p-value
res$p.value
# printing the mean
res$estimate
# printing the confidence interval
res$conf.int

如果我的问题是检验男生的平均体重是不是比女生的要重?当原假设是a>b,alternative假设就是a<b,相应参数alternativeless

t.test(weight ~ group, data = my_data,
        var.equal = TRUE, alternative = "less")

非参数方法

当我们对数据的分布情况不了解时,使用非参数检验方法。

当数据不是标准格式时,

# 1) Compute two-samples Wilcoxon test - Method 1: The data are saved in two different numeric vectors.

res <- wilcox.test(women_weight, men_weight)
res

当数据为标准格式时,

# 2) Compute two-samples Wilcoxon test - Method 2: The data are saved in a data frame.

res <- wilcox.test(weight ~ group, data = my_data,
                   exact = FALSE)
res

# Print the p-value only
res$p.value
posted @ 2020-03-22 16:27  blairD  阅读(644)  评论(0)    收藏  举报