如何将两组配对t检验结果转为Word表格?R语言报错求助
配对t检验结果导出Word的问题解决
问题说明
我尝试将两次配对t检验的结果整合为单个表格并导出到Microsoft Word,但触发错误:Error: (converted from warning) package ‘flextable’ was built under R version 4.2.3。虽然已经更新了R版本,但还是出现这个版本兼容问题。
现有代码
原始配对t检验代码
## 检验边缘存在对鸟类捕食标记量的影响 library(tidyverse) # 筛选样地位置为Edge和Center的数据 filtered_data <- subset(Yes, `Position within the plot` %in% c("Edge", "Center")) print(result <- t.test(`Amount of bird markings per caterpillar` ~ `Position within the plot`, data = filtered_data, paired = TRUE)) ## 检验边缘缺失对鸟类捕食标记量的影响 # 筛选样地位置为Edge和Center的数据 filtered_datan <- subset(no, `Position within the plot` %in% c("Edge", "Center")) print(resultn <- t.test(`Amount of bird markings per caterpillar` ~ `Position within the plot`, data = filtered_datan, paired = TRUE))
尝试过的导出代码
result <- data.frame( statistic = result$statistic, df = result$parameter, p_value = result$p.value, conf_int_lower = result$conf.int[1], conf_int_upper = result$conf.int[2], mean_difference = result$estimate ) # 导出为CSV write.csv(result, file = "t_test_results.csv", row.names = FALSE) tab_model(model, file = "t_test_results.doc", show.se = TRUE, show.std = TRUE, show.stat = TRUE, show.ci = 0.95, show.est = TRUE) library(flextable) # 读取CSV并转换为flextable result <- read.csv("t_test_results.csv") ft <- flextable(result) # 修改列名 colnames(ft) <- c("Statistic", "df", "p-value", "Conf. Int. Lower", "Conf. Int. Upper", "Mean Difference")
解决步骤
1. 修复flextable版本兼容问题
更新R后,旧版本的flextable是基于旧R版本编译的,必须重新安装适配当前R版本的包:
install.packages("flextable")
如果提示需要从源码安装,选择同意,这样包会重新编译适配你的当前R版本。
2. 优化结果整合与导出流程
用broom包简化结果提取,合并两次检验结果后直接用flextable导出到Word:
library(tidyverse) library(broom) library(flextable) # 处理第一次检验(有边缘组) filtered_data <- subset(Yes, `Position within the plot` %in% c("Edge", "Center")) result <- t.test(`Amount of bird markings per caterpillar` ~ `Position within the plot`, data = filtered_data, paired = TRUE) result_tidy <- tidy(result) %>% mutate(检验组 = "有边缘组") # 处理第二次检验(无边缘组) filtered_datan <- subset(no, `Position within the plot` %in% c("Edge", "Center")) resultn <- t.test(`Amount of bird markings per caterpillar` ~ `Position within the plot`, data = filtered_datan, paired = TRUE) resultn_tidy <- tidy(resultn) %>% mutate(检验组 = "无边缘组") # 合并两次结果并整理列名 combined_results <- bind_rows(result_tidy, resultn_tidy) %>% select(检验组, statistic, df, p.value, conf.low, conf.high, estimate) %>% rename( "统计量(t值)" = statistic, "自由度(df)" = df, "p值" = p.value, "置信区间下限" = conf.low, "置信区间上限" = conf.high, "均值差" = estimate ) # 生成表格并导出到Word ft <- flextable(combined_results) %>% set_caption("配对t检验结果:边缘存在与否对鸟类捕食标记量的影响") %>% autofit() save_as_docx(ft, path = "t检验结果汇总.docx")
注意事项
- 确保
Yes和no两个数据框存在,且列名与代码中的完全匹配; - 如果Windows系统安装flextable时编译失败,需要先安装Rtools;Mac系统则需要安装Xcode命令行工具。
内容的提问来源于stack exchange,提问作者Madelein Victor
相关产品推荐
相关产品推荐

