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.
You first include the character f before the opening and closing quotation marks, inside the print() function. To print a variable with a string in one line, you again include the character f in the same place – right before the quotation marks.
You can put one or more print statements inside the function definition and not bother to return anything from the function (the value None will be returned).
This is done by using the “+” character between two variables or strings. This way we can use Python to print variable values along with the string.
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With