Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print or display variable inside function

Tags:

r

printing

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.

like image 605
Mark Miller Avatar asked Mar 30 '14 03:03

Mark Miller


People also ask

How do you print a variable inside a function?

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.

Can you print inside a function?

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

How do you print a variable inside a string in Python?

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.


1 Answers

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))
}
like image 114
Gary Weissman Avatar answered Sep 21 '22 07:09

Gary Weissman