问题
Is there a way to print
or display the value of a variable while inside a function, as opposed to printing the value outside the function after the function has been called?
I am virtually certain there is and thought the code was called reveal
or something similar, but I cannot recall the correct term.
my.function <- function(x) {
y <- x^2
# reveal(y)
# display(y)
# desired result is to print or display here:
# [1] 16
cat(y)
print(y)
return(y)
}
x <- 4
my.function(x)
#16[1] 16
#[1] 16
cat(y)
, print(y)
and return(y)
all print outside the function. Thank you for any advice.
EDIT
I found a similar question here:
https://stat.ethz.ch/pipermail/r-help/2002-November/027348.html
The response to that question from Peter Dalgaard was to uncheck an option called buffered output
under the Misc
tab. However, that does not seem to be working in my case. Perhaps the questions are unrelated.
回答1:
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.
> 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
回答2:
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))
}
回答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
来源:https://stackoverflow.com/questions/22740082/print-or-display-variable-inside-function