使用write.csv导出edge_table时estimate列显示异常的解决方法
问题描述
我创建了如下数据:
class.df <- data.frame( A = sample(1:2, 100, replace=TRUE), B = sample(1:2, 100, replace=TRUE), C = sample(1:2, 100, replace=TRUE), D = sample(1:2, 100, replace=TRUE) ) ids_df <- t(combn(names(class.df), 2)) fisher_tests <- apply(ids_df, 1, function(i) tryCatch(fisher.test(table(class.df[,i])), error = function(e) NA_real_)) edge_table <- cbind(ids_df, t(sapply(fisher_tests, "[", c("p.value", "estimate")))) edge_table
执行write.csv(edge_table,"/Users/Results/EE2.csv")导出后,打开CSV文件发现最后一列estimate显示怪异的矩阵格式,而非R中显示的数值,请问该如何解决?
解决方案
问题根源
fisher.test()返回的estimate是一个带命名的向量(对应2x2列联表的优势比(odds ratio)),直接用sapply提取时会保留向量结构,合并到edge_table后,这个列实际是嵌套的向量类型,导出CSV时就会显示成类似c(0.87)这类不符合预期的格式。
修复代码
方法一:重构结果提取逻辑
在处理每个Fisher检验结果时,直接提取estimate的数值(而非保留向量结构):
class.df <- data.frame( A = sample(1:2, 100, replace=TRUE), B = sample(1:2, 100, replace=TRUE), C = sample(1:2, 100, replace=TRUE), D = sample(1:2, 100, replace=TRUE) ) ids_df <- t(combn(names(class.df), 2)) fisher_tests <- apply(ids_df, 1, function(i) { # 捕获异常并处理 res <- tryCatch(fisher.test(table(class.df[,i])), error = function(e) NULL) if (!is.null(res)) { # 提取p.value和estimate的纯数值,unname去掉命名,[1]取唯一的优势比值 list(p.value = res$p.value, estimate = unname(res$estimate)[1]) } else { list(p.value = NA_real_, estimate = NA_real_) } }) # 将list转为矩阵后合并 edge_table <- cbind(ids_df, do.call(rbind, fisher_tests)) # 导出CSV write.csv(edge_table,"/Users/Results/EE2.csv", row.names = FALSE)
方法二:简化原代码的提取步骤
直接在原sapply中对estimate做数值提取:
class.df <- data.frame( A = sample(1:2, 100, replace=TRUE), B = sample(1:2, 100, replace=TRUE), C = sample(1:2, 100, replace=TRUE), D = sample(1:2, 100, replace=TRUE) ) ids_df <- t(combn(names(class.df), 2)) fisher_tests <- apply(ids_df, 1, function(i) tryCatch(fisher.test(table(class.df[,i])), error = function(e) NA_real_)) # 修改提取逻辑,直接取estimate的数值 edge_table <- cbind(ids_df, t(sapply(fisher_tests, function(x) { if (!is.na(x)) { c(p.value = x$p.value, estimate = unname(x$estimate)[1]) } else { c(p.value = NA_real_, estimate = NA_real_) } }))) # 导出CSV write.csv(edge_table,"/Users/Results/EE2.csv", row.names = FALSE)
验证效果
处理后的edge_table中,estimate列会是纯数值类型,导出的CSV文件里该列将正常显示数字,不会再出现怪异的向量/矩阵格式。
内容的提问来源于stack exchange,提问作者Aryh
相关产品推荐
相关产品推荐

