1

我想知道如何从 R 脚本中导出文本文件。无论结果如何,我都想预设一些要打印的文本,但我也想在我的文本文件中添加可能更改的变量。我知道如何做到这一点的唯一方法是使用sinkand cat。问题是我必须cat为每条独立的线创建一个。有没有办法写一个大段落而不cat在每一行使用?

x = 1:10
sink("~/Desktop/TEST.txt", type=c("output", "message"), append = FALSE)
"===============================================================  \n
NEW MODEL  
===============================================================  
Summary of the model:"  
x 
# model.summary$BUGSoutput$sims.list
sink(NULL)

输出如下所示:

[1] "===============================================================  \n\nNEW MODEL  \n===============================================================  \nSummary of the model:"
 [1]  1  2  3  4  5  6  7  8  9 10

但我更喜欢这样的东西:

===============================================================
NEW MODEL
===============================================================

Summary of the model:
1  2  3  4  5  6  7  8  9 10

你可以这样写(但有没有办法不在每一行写 cat ?):

x = 1:10
sink("~/Desktop/TEST.txt", type=c("output", "message"), append = FALSE)
cat("===============================================================\n")
cat("NEW MODEL\n")
cat("===============================================================\n")
cat("Summary of the model:\n")
x 
cat("# model.summary$BUGSoutput$sims.list\n")
sink(NULL)

要得到这个:

===============================================================
NEW MODEL
===============================================================
Summary of the model:
 [1]  1  2  3  4  5  6  7  8  9 10
# model.summary$BUGSoutput$sims.list

但有趣的是,这不起作用:

yo <- function(x) {
  sink("~/Desktop/potato.txt", type="output")
  writeLines("===============================================================
NEW MODEL
===============================================================
Summary of the model:")
x
# other stuff
  sink()

}

yo(1:10)

输出:

===============================================================
NEW MODEL
===============================================================
Summary of the model:
4

1 回答 1

1

使用?writeLines。考虑:

sink(<file name>, type="output")
writeLines("===============================================================
NEW MODEL
===============================================================
Summary of the model:")
summary(model)
# other stuff
sink()
于 2016-09-10T21:11:33.657 回答