当前位置:  开发笔记 > 后端 > 正文

如何将所有控制台输出保存到R中的文件?

如何解决《如何将所有控制台输出保存到R中的文件?》经验,为你挑选了2个好方法。

我想将所有控制台文本重定向到一个文件.这是我尝试过的:

> sink("test.log", type=c("output", "message"))
> a <- "a"
> a
> How come I do not see this in log
Error: unexpected symbol in "How come"

这是我在test.log中得到的:

[1] "a"

这是我在test.log中想要的:

> a <- "a"
> a
[1] "a"
> How come I do not see this in log
Error: unexpected symbol in "How come"

我究竟做错了什么?谢谢!



1> Tommy..:

你必须分别下沉"输出"和"消息"(该sink功能只查看第一个元素type)

现在,如果您还想记录输入,则将其放入脚本中:

script.R

1:5 + 1:3   # prints and gives a warning
stop("foo") # an error

并在提示:

con <- file("test.log")
sink(con, append=TRUE)
sink(con, append=TRUE, type="message")

# This will echo all input and not truncate 150+ character lines...
source("script.R", echo=TRUE, max.deparse.length=10000)

# Restore output to console
sink() 
sink(type="message")

# And look at the log...
cat(readLines("test.log"), sep="\n")


@ user443854如果是这样,最好放弃交互式工作并使用脚本.
@ user443854:是的,你能把代码放在脚本中吗?在这种情况下,源("script.R",echo = TRUE)将起作用 - 如果您重定向输出,如上所述.
@ user443854:是的,使用`max.deparse.length`参数.我更新了答案.

2> 小智..:

如果您可以访问命令行,则可能更喜欢使用R CMD BATCH从命令行运行脚本.

==开始script.R ==的内容

a <- "a"
a
How come I do not see this in log

==结束script.R ==的内容

在命令提示符下(许多un*x变体中的"$",Windows中的"C:>"),运行

$ R CMD BATCH script.R &

尾部"&"是可选的,并在后台运行命令.日志文件的默认名称在扩展名后附加了"out",即script.Rout

==开始script.Rout ==的内容

R version 3.1.0 (2014-04-10) -- "Spring Dance"
Copyright (C) 2014 The R Foundation for Statistical Computing
Platform: i686-pc-linux-gnu (32-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

[Previously saved workspace restored]

> a <- "a"
> a
[1] "a"
> How come I do not see this in log
Error: unexpected symbol in "How come"
Execution halted

==结束script.Rout ==的内容

推荐阅读
刘美娥94662
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有