在R中将p值写入文件

5

能有人帮我解决这段代码吗。在一个循环中,我将p值保存在f中,然后我想将p值写入文件,但我不知道要使用哪个函数来进行文件写入。我使用write函数时出现了错误。

{
f = fisher.test(x, y = NULL, hybrid = FALSE, alternative = "greater",
                conf.int = TRUE, conf.level = 0.95, simulate.p.value = FALSE)

write(f, file="fisher_pvalues.txt", sep=" ", append=TRUE)
}

Error in cat(list(...), file, sep, fill, labels, append) : 
  argument 1 (type 'list') cannot be handled by 'cat'

1
只是想感谢 @Helen 提供完整的代码和完整的错误信息。 是一个新手问题,但有了这些信息,提供正确的答案就很容易了。 - Carl Witthoft
2个回答

6

如果你阅读文档,fisher.test 的返回值如下:

Value:

 A list with class ‘"htest"’ containing the following components:

p.value: the p-value of the test.

conf.int: a confidence interval for the odds ratio. Only present in the 2 by 2 case and if argument ‘conf.int = TRUE’.

等等,R不知道如何将类似那样的东西写入文件。更准确地说,它不知道你想要它如何写入文件。

如果你只想写出P值,那么获取P值并进行写入:

 write(f$p.value,file="foo.values",append=TRUE)

或者你可以使用 save 将整个对象写入文件。 - joran
@joran -- 看起来 Helen 想要结果保存在一个 *.txt 文件中,所以值得注意的是 save 函数会将对象以 R 特定的二进制格式写入文件。 - Josh O'Brien

4

f是一个属于类'htest'的对象,因此将其写入文件时会写入远不止p值。

如果您只想将结果以它们在屏幕上出现的形式简单保存到文件中,您可以使用capture.output()来实现:

Convictions <-
   matrix(c(2, 10, 15, 3),
          nrow = 2,
          dimnames =
          list(c("Dizygotic", "Monozygotic"),
               c("Convicted", "Not convicted")))
 f <- fisher.test(Convictions, alternative = "less")

 capture.output(f, file="fisher_pvalues.txt", append=TRUE)

更有可能的是,你只想存储p值。在这种情况下,您需要在将其写入文件之前,从f中提取它,使用类似以下代码的代码:

 write(paste("p-value from Experiment 1:", f$p.value, "\n"), 
       file = "fisher_pvalues.txt", append=TRUE)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接