print or display variable inside function

You can put print() calls (or cat() calls for that matter) inside the function and if the execution reaches that point, then an output will be produced on the console even if an error later occurs later in execution. (It's possible that flush.console() will be needed if the IDE you are using is set for "buffered output".)

 > myf <- function(x){ print(x); y <- x^2; print(y); error() }
> myf(4)
[1] 4
[1] 16
Error in myf(4) : could not find function "error"

It's probably more elegant to use the browser() function as the debugging route. You set up its operation by changing options():

> options(error=recover)
> myf(4)
[1] 4
[1] 16
Error in myf(4) : could not find function "error"

Enter a frame number, or 0 to exit   

1: myf(4)

Selection: 1
Called from: top level 
Browse[1]> x
[1] 4
Browse[1]> y
[1] 16
Browse[1]>    # hit a <return> to exit the browser 

Enter a frame number, or 0 to exit   

1: myf(4)

Selection: 0   # returns you to the console

I like to use the message function to print for debugging, since it seems to reach the console from whatever dark depths it might be emitting from. For example:

somefunc <- function(x) {
       message(paste('ok made it this far with x=',x))
       # some stuff to debug
       message(paste('ok made it this far with x^2=',x^2))
       # some more stuff to debug
       message(paste('ok made it to the end of the function with x^3=',x^3))
}

When I asked this question I might have been thinking of the show function which allows you to see the values of a variable without including that variable in the return statement. Although, the show command prints values outside of the function.

my.function <- function(x) {
     y <- x^2
     show(y)
     show(length(y))
     z <- y + x
     return(z)
}

x <- 1:10

my.function(x)

 # [1]   1   4   9  16  25  36  49  64  81 100
 # [1] 10
 # [1]   2   6  12  20  30  42  56  72  90 110

EDIT: March 19, 2021

Another way to view results from inside a function is to send an object to a global variable. This might be helpful in locating errors inside a function.

my.function <- function(x) {
     y <- x^2
     y <<- y
     z <- y + x
     z <<- z
     return(z)
}
y
#[1]   1   4   9  16  25  36  49  64  81 100
z
#[1]   2   6  12  20  30  42  56  72  90 110
x <- 1:10
my.function(x)
#[1]   2   6  12  20  30  42  56  72  90 110

Tags:

Printing

R