104

I want to redirect all console text to a file. Here is what I tried:

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

Here is what I got in test.log:

[1] "a"

Here is what I want in test.log:

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

What am I doing wrong? Thanks!

user443854
  • 7,096
  • 13
  • 48
  • 63

10 Answers10

128

You have to sink "output" and "message" separately (the sink function only looks at the first element of type)

Now if you want the input to be logged too, then put it in a script:

script.R

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

And at the prompt:

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")
Tommy
  • 39,997
  • 12
  • 90
  • 85
  • 2
    This prints only output, but does not print input. I want to see input line, e.g. `1:5 + 1:3`, followed by its output, then next, etc. The reason I want to produce this type of log is because I have a program that takes 30+ GBytes of RAM to run. I run it in amazon cloud and save output from regressions to individual files. I want to be able to quickly find the code that produced each file by looking at the log. Note: if I just cut-n-paste console output, that does it. – user443854 Aug 17 '11 at 17:54
  • 6
    @user443854 If so, it is a better idea to drop interactive work and work with scripts. – mbq Aug 17 '11 at 18:03
  • 5
    @user443854: Yeah, can you put the code in a script? In that case source("script.R", echo=TRUE) would do the trick - if you redirect the output as explained above. – Tommy Aug 17 '11 at 18:04
  • @Tommy You the man. Thanks! I do have an .R script, but I was pasting it into the interactive session on remote box. Sourcing it does the trick. – user443854 Aug 17 '11 at 18:19
  • @Tommy Almost. Long lines in the log file are truncated, e.g. `reg.blah.blah <- glm(ref~as.factor(code))+level+year,data=join, .... [TRUNCATED]`. Any idea how to get R to print the whole thing? – user443854 Aug 17 '11 at 19:17
  • 2
    @user443854: Yeah, use the `max.deparse.length` argument. I updated the answer. – Tommy Aug 17 '11 at 19:29
  • remember use the `echo=TRUE` in `source` function – JuanPablo Oct 28 '13 at 19:32
  • any way to sink messages with SPLIT = TRUE? – jangorecki Dec 17 '13 at 22:06
  • Thanks this was very helpful! – Timothy055 Jul 25 '15 at 20:33
  • This code helped me to redirect the output from a function (Rtsne) into the log-file when using futile.logger. I used the split-option to have it in the console too (sink(con, append=T, split=T)). – Shadow Nov 23 '16 at 13:36
  • I should add that "file(log_filename, open="a+")", i.e., "open="a+"", had to be used to append to the file too, not just to sink(). – Shadow Nov 23 '16 at 14:49
  • can you use this approach if you want to run a script from bash, `RScript x.r` – 3pitt Dec 11 '17 at 14:47
  • N.B. that (as of R 3.4.1) the R help for `sink` warns, "Do not sink the messages stream unless you understand the source code implementing it and hence the pitfalls." (I don't understand said source, so I can't comment on what those pitfalls might be.) – calavicci Aug 17 '18 at 18:27
15

If you have access to a command line, you might prefer running your script from the command line with R CMD BATCH.

== begin contents of script.R ==

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

== end contents of script.R ==

At the command prompt ("$" in many un*x variants, "C:>" in windows), run

$ R CMD BATCH script.R &

The trailing "&" is optional and runs the command in the background. The default name of the log file has "out" appended to the extension, i.e., script.Rout

== begin contents of 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

== end contents of script.Rout ==

Gaius Augustus
  • 940
  • 2
  • 15
  • 37
WMash
  • 407
  • 4
  • 5
  • 1
    I'm utilizing zsh, for some reason `R CMD BATCH script.R &` doesn't work. – redeemefy Sep 10 '16 at 20:10
  • I work with command line and `screen`, so hiding the process (with trainling `&`) is not really a necessity for me. But even without the `&`, I do not get any output to the console anymore. **Is it possible to get both (console output AND the log in xy.Rout)?** – Honeybear Jul 11 '22 at 08:41
5

If you are able to use the bash shell, you can consider simply running the R code from within a bash script and piping the stdout and stderr streams to a file. Here is an example using a heredoc:

File: 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 

Then when you run the script with both stderr and stdout piped to a log file:

$ 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

Other things to look at for this would be to try simply pipping the stdout and stderr right from the R heredoc into a log file; I haven't tried this yet but it will probably work too.

user5359531
  • 3,217
  • 6
  • 30
  • 55
3

Run R in emacs with ESS (Emacs Speaks Statistics) r-mode. I have one window open with my script and R code. Another has R running. Code is sent from the syntax window and evaluated. Commands, output, errors, and warnings all appear in the running R window session. At the end of some work period, I save all the output to a file. My own naming system is *.R for scripts and *.Rout for save output files. Here's a screenshot with an example.Screenshot writing and evaluating R with Emacs/ESS.

3

You can't. At most you can save output with sink and input with savehistory separately. Or use external tool like script, screen or tmux.

mbq
  • 18,510
  • 6
  • 49
  • 72
2

You can print to file and at the same time see progress having (or not) screen, while running a R script.

When not using screen, use R CMD BATCH yourscript.R & and step 4.

  1. When using screen, in a terminal, start screen

     screen
    
  2. run your R script

     R CMD BATCH yourscript.R
    
  3. Go to another screen pressing CtrlA, then c

  4. look at your output with (real-time):

     tail -f yourscript.Rout
    
  5. Switch among screens with CtrlA then n

Ferroao
  • 3,042
  • 28
  • 53
1

To save text from the console: run the analysis and then choose (Windows) "File>Save to File".

SabreWolfy
  • 5,392
  • 11
  • 50
  • 73
1

Set your Rgui preferences for a large number of lines, then timestamp and save as file at suitable intervals.

Alan Engel
  • 56
  • 2
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

Prateek Sharma
  • 1,371
  • 13
  • 11
-1

This may not work for your needs, but one solution might be to run your code from within an Rmarkdown file. You could write both the code and console output to HTML/PDF/Word.

user3667133
  • 147
  • 2
  • 9
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 18 '21 at 01:13