Pretty printable R function
I am working on text with inline R code. I am using Sweave to create PDF documents. I would like to print the functions written in my PDF, but print(f)
where f is an arbitrary function removes some key aspects like the function name. For example:
f <- function(x, y = 2) {
return(x^y)
}
print(f)
gives the following:
> source('~/.active-rstudio-document')
function(x, y = 2) {
return(x^y)
}
Is there some version print
or some similar function that will print something that I can cut and paste right back into R while keeping the function declaration (part f <-
)? Also, and this is kind of by design, is there a way to set the maximum width in characters?
+3
source to share
1 answer
Probably the best way, but something like this:
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)
## }
+5
source to share