如何使用 R 在文件中获取名为 shapiro.test() 的函数的输出?

how to get the output of a function called shapiro.test() in a file using R?

假设您有服用药物前后的数据。检验是否因药物而存在显着差异

>set.seed(10)
>before = rnorm(100)
>set.seed(20)
>after = rnorm(100, mean = 2)
>d = after - before
>shapiro.test(d)

此函数 'shapiro.test(d)' 将打印此输出:

Shapiro-Wilk normality test
data: d
W = 0.98326, p-value = 0.2363

现在,如何在文件中打印此输出?有没有可以做到这一点的功能?

我们可以捕获输出并使用 cat 将其写入文本文件。

cat(paste0(capture.output(shapiro.test(d)),collapse = '\n'), file = 'result.txt')