Ido Hatam
Ido Hatam

Reputation: 123

Is there a way to log or record the output from R functions?

Let's say I am running some code in R. As an example:

x <- 1

if (x == 0.1){
    print('X = 0.1')
    } else if (x > 0.1){
    print('X is bigger than 0.1 ')
    } else {
    print('X is smaller than 0.1')
    }

If I look at the history file in R studio it will show me that I ran this conditional statement but it will not show me the outcome (i.e. X is bigger than 0.1).

Is there a way to automatically log the output in R or R studio?

Upvotes: 9

Views: 16943

Answers (3)

Andy Borst
Andy Borst

Reputation: 338

One can search for "log output packages R" or something similar . Here is one example I pulled from the search.

library(log4r)
#> 
#> Attaching package: 'log4r'
#> The following object is masked from 'package:base':
#> 
#>     debug

my_logfile = "my_logfile.txt"

my_console_appender = console_appender(layout = default_log_layout())
my_file_appender = file_appender(my_logfile, append = TRUE, 
                            layout = default_log_layout())

my_logger <- log4r::logger(threshold = "INFO", 
                appenders= list(my_console_appender,my_file_appender))

log4r_info <- function() {
  log4r::info(my_logger, "Info_message.")
}

log4r_error <- function() {
  log4r::error(my_logger, "Error_message")
}

log4r_debug <- function() {
  log4r::debug(my_logger, "Debug_message")
}

log4r_debug() # will not trigger log entry because threshold was set to INFO

log4r_info() 
#> INFO  [2020-07-01 12:48:02] Info_message.

log4r_error() 
#> ERROR [2020-07-01 12:48:02] Error_message

readLines(my_logfile)
#> [1] "INFO  [2020-07-01 12:48:02] Info_message."
#> [2] "ERROR [2020-07-01 12:48:02] Error_message"

Upvotes: 0

Andy Clifton
Andy Clifton

Reputation: 5056

You need to combine sink() and cat().

First, in your script or at the console, you can use sink() to start your log file and send text to the terminal at the same time:

sink("myfile.log", append=TRUE, split=TRUE)

This will also append data to an existing log file.

Then replace print with cat in your functions, so that output is captured by the log file. So, in your example:

sizex <- function(x){
if (x ==0.1){
    cat('X = 0.1')
    } else if (x > 0.1){
    cat('X is bigger than 0.1 ')
    } else {
    cat('X is smaller than 0.1')
    }
}

and then we'd use the function:

x <- 1
sizex(x)

If for some reason you want to stop logging, just type sink(). The nice thing about cat() is that it will revert to pushing text to the the terminal without any effort on your behalf if you are using sink().

N.B. If you want to know the difference between cat and print, see What is the difference between cat and print?.

Upvotes: 4

ddunn801
ddunn801

Reputation: 1890

Direct output to a log file and screen:

sink("myfilename", append=FALSE, split=TRUE)  # for screen and log

Return output to the screen only:

sink()

From Quick-R

Upvotes: 11

Related Questions