其他
使用rstatix优雅的进行统计分析
欢迎关注R语言数据分析指南
❝本节来介绍如何使用「rstatix」包来进行统计分析,下面通过一个小案例来进行展示
❞
清理变量
rm(list=ls())
安装并加载R包
package.list=c("tidyverse","ggprism","ggsci","rstatix","patchwork")
for (package in package.list) {
if (!require(package,character.only=T, quietly=T)) {
install.packages(package)
library(package, character.only=T)
}
}
计算组内p值
df_p_val1 <- ToothGrowth %>%
rstatix::group_by(dose) %>%
rstatix::t_test(len ~ supp) %>%
rstatix::adjust_pvalue(p.col = "p", method = "bonferroni") %>%
rstatix::add_significance(p.col = "p.adj") %>%
rstatix::add_xy_position(x = "dose", dodge = 0.8)
# A tibble: 3 × 16
dose .y. group1 group2 n1 n2 statistic df p p.adj p.adj.signif y.position groups x xmin xmax
<dbl> <chr> <chr> <chr> <int> <int> <dbl> <dbl> <dbl> <dbl> <chr> <dbl> <named list> <dbl> <dbl> <dbl>
1 0.5 len OJ VC 10 10 3.17 15.0 0.00636 0.0191 * 24.2 <chr [2]> 1 0.825 1.18
2 1 len OJ VC 10 10 4.03 15.4 0.00104 0.00312 ** 30.0 <chr [2]> 2 1.82 2.17
3 2 len OJ VC 10 10 -0.0461 14.0 0.964 1 ns 36.6 <chr [2]> 3 2.82 3.18
组间p值
df_p_val2 <- rstatix::wilcox_test(ToothGrowth, len ~ dose,
p.adjust.method = "bonferroni") %>%
rstatix::add_xy_position()
.y. group1 group2 n1 n2 statistic p p.adj p.adj.signif y.position groups xmin xmax
<chr> <chr> <chr> <int> <int> <dbl> <dbl> <dbl> <chr> <dbl> <named list> <dbl> <dbl>
1 len 0.5 1 20 20 33.5 0.00000702 0.0000211 **** 35.4 <chr [2]> 1 2
2 len 0.5 2 20 20 1.5 0.0000000841 0.000000252 **** 37.6 <chr [2]> 1 3
3 len 1 2 20 20 61 0.000177 0.000531 *** 39.9 <chr [2]> 2 3
数据可视化
ToothGrowth %>% ggplot(aes(x = factor(dose),y=len)) +
geom_boxplot(aes(fill=supp),width = 0.5,show.legend = T) +
geom_point(aes(x = factor(dose), y = len, color = supp), position=position_jitterdodge(), alpha = 0.6) +
theme_prism() +
coord_cartesian(ylim = c(0,45)) +
theme(legend.position = "top")+
scale_fill_jco()+
add_pvalue(df_p_val1, xmin = "xmin", xmax = "xmax",
label = "p = {p.adj}", tip.length = 0) +
add_pvalue(df_p_val2, label = "p = {p.adj}",
tip.length = 0.01, bracket.nudge.y = 2, step.increase = 0.01)
❝可以看到使用「rstatix」进行统计分析还是非常方便的,更多资料请查阅官方文档
❞
欢迎大家扫描下方二位码加入「QQ交流群」,与全国各地上千位小伙伴交流
「关注下方公众号下回更新不迷路」,如需要加入微信交流群可添加小编微信,请备注单位+方向+姓名
往期推荐