2

Say I have a function defined as follows:

myFun <- function(x, y) {
  return(2*x + y)
}

I can print the function's definition by simply typing myFun without parentheses in the console:

> myFun
function(x, y) {
  return(2*x + y)
}

How can I return (or print) both the name and the function? That is, I want the console (printed) output to be:

myFun <- function(x, y) {
  return(2*x + y)
}

If it's not possible to print the code that defined the function, is there a way to cat or print in such a way that I can prepend the normal result of myFun with the text "myFun <- "?

JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116

1 Answers1

5

This probably isn't very robust, but here's a start:

myFun <- function(x, y) {
  return(2*x + y)
}

myfunprint = function(fun) {
  cl = match.call()
  cat(paste(as.character(cl$fun), "<- "))
  print(fun)
  invisible()
}

myfunprint(myFun)
# myFun <- function(x, y) {
#   return(2*x + y)
# }
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • This works -- going to leave this unanswered for a few days to see if others chime in. What's `invisible()` doing here? – JasonAizkalns Jun 28 '23 at 12:16
  • It makes it so the function doesn't "return" anything visibly - though I just tried and it seems to work just fine without it. – Gregor Thomas Jun 28 '23 at 13:30
  • Thanks. Related/similar question for shiny if you're interested: https://stackoverflow.com/questions/76573592/how-to-print-the-source-code-of-different-shiny-server-components-and-outputs – JasonAizkalns Jun 28 '23 at 13:33