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?.