Search code examples
rlatexsweave

Pretty printing R function


I am working on some text with embedded R code. I am using Sweave to produce PDF documents. I'd like to print the functions as written into my PDF, but print(f) where f is an arbitrary function eliminates some of the key aspects, like the function name. For instance:

f <- function(x, y = 2) {
  return(x^y)
}

print(f)

yields this:

> source('~/.active-rstudio-document')
function(x, y = 2) {
  return(x^y)
}

Is there some version of print or some similar function that would print something I can cut and paste directly back into R, preserving the function declaration (the f <- part)? Also, and this is kind of an after thought, is there a way to set the maximum width in characters?


Solution

  • There's probably a better way but something like this would work:

    f <- function(x, y = 2) {
      return(x^y)
    }
    
    pretty <- function(fun){
        captured <- capture.output(fun)
        captured[1] <- paste(as.character(substitute(fun)), "<-", captured[1])
    
        cat(paste(captured, collapse="\n"))
    }
    
    pretty(f)
    
    ## f <- function(x, y = 2) {
    ##   return(x^y)
    ## }