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

105

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

> 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"

我做错了什么?谢谢!


你可以看一下这个教程:https://statisticsglobe.com/r-save-all-console-input-output-to-file - Joachim Schork
10个回答

131
你必须分别将 "output" 和 "message" 传递给 "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")

2
这仅打印输出,但不打印输入。我想看到每一行的输入,例如 1:5 + 1:3,然后是它的输出,然后是下一个,等等。我要生成这种类型的日志的原因是,我有一个需要30多GB RAM才能运行的程序。我在亚马逊云中运行它,并将回归分析的输出保存到各个文件中。通过查看日志,我希望能够快速找到生成每个文件的代码。注意:如果只是剪切并粘贴控制台输出,那就可以了。 - user443854
6
如果是这样的话,最好放弃交互式工作,转而使用脚本进行工作。 - mbq
5
可以将代码放在脚本中吗?这样的话,如果按照上面解释的方式重定向输出,使用source("script.R", echo=TRUE)就可以了。 - Tommy
2
@user443854:是的,使用 max.deparse.length 参数。我已更新答案。 - Tommy
请在source函数中使用echo=TRUE来记住输出。 - JuanPablo
显示剩余8条评论

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

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


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

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

== script.R 结束内容 ==

在命令提示符下(在许多 unix 变体中为 "$",在 windows 中为 "C:>"),运行

$ R CMD BATCH script.R &

结尾的"&"是可选的,可以将命令在后台运行。 log文件的默认名称为扩展名加上"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 的结束内容 ==


1
我正在使用zsh,但不知何故,“R CMD BATCH script.R&”无法工作。 - redeemefy
我使用命令行和screen,因此对我来说隐藏进程(使用结尾的&)并不是必需的。但即使没有&,我也无法再在控制台上获得任何输出。有可能同时获得控制台输出和xy.Rout中的日志吗? - Honeybear

5
如果你能使用bash shell,可以考虑在bash脚本中运行R代码并将stdout和stderr流导入文件中。下面是一个使用heredoc的例子:
文件:test.sh
#!/bin/bash
# this is a bash script
echo "Hello World, this is bash"

test1=$(echo "This is a test")

echo "Here is some R code:"

Rscript --slave --no-save --no-restore - "$test1" <<EOF
  ## R code
  cat("\nHello World, this is R\n")
  args <- commandArgs(TRUE)
  bash_message<-args[1]
  cat("\nThis is a message from bash:\n")
  cat("\n",paste0(bash_message),"\n")
EOF

# end of script 

当您运行脚本并将stderr和stdout都导向日志文件时:

$ chmod +x test.sh
$ ./test.sh
$ ./test.sh &>test.log
$ cat test.log
Hello World, this is bash
Here is some R code:

Hello World, this is R

This is a message from bash:

 This is a test

对于这个问题,另一个可以尝试的方法是将R heredoc中的stdout和stderr直接传输到日志文件中;虽然我还没有尝试过,但这也可能有效。


3
使用ESS(Emacs Speaks Statistics)r-mode在emacs中运行R。我打开一个窗口来写我的脚本和R代码,另一个窗口则运行R。代码从语法窗口发送并进行评估。命令、输出、错误和警告都出现在正在运行的R窗口会话中。在一段时间的工作结束后,我将所有的输出保存到文件中。我的命名系统是*.R用于脚本,*.Rout用于保存输出文件。以下是一个包含示例的屏幕截图:Screenshot writing and evaluating R with Emacs/ESS.

3

你不能这样做。最多只能使用 sink 来保存输出,使用 savehistory 来保存输入,或者使用外部工具,例如 scriptscreentmux


2

你可以在运行 R 脚本时,将输出打印到文件并同时查看进度(或不查看)screen

如果不使用 screen,请使用 R CMD BATCH yourscript.R & 并执行第四步。

使用 screen,在终端中启动 screen:
``` screen ```
运行你的 R 脚本:
``` R CMD BATCH yourscript.R ```
按下 CtrlA,然后按 c 进入另一个 screen。
实时查看输出:
``` tail -f yourscript.Rout ```
使用 CtrlA 然后 n 在不同的 screen 之间切换。

1

将您的Rgui首选项设置为大量行,然后在适当的间隔时间戳并保存为文件。


2
请详细说明。 - bunbun

1

要从控制台保存文本:运行分析,然后选择(Windows)“文件>保存到文件”。


1
  1. If you want to get error messages saved in a file

    zz <- file("Errors.txt", open="wt")
    sink(zz, type="message")
    

    the output will be:

    Error in print(errr) : object 'errr' not found
    Execution halted
    

    This output will be saved in a file named Errors.txt

  2. In case, you want printed values of console to a file you can use 'split' argument:

    zz <- file("console.txt", open="wt")
    sink(zz,  split=TRUE)
    print("cool")
    print(errr)
    

    output will be:

    [1] "cool"
    

    in console.txt file. So all your console output will be printed in a file named console.txt


-1
这可能不适用于你的需求,但一个解决方案是在Rmarkdown文件中运行代码。你可以将代码和控制台输出写入HTML/PDF/Word文件中。

你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

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