简体   繁体   中英

Store function definition as a character object

Take the following example function

temp_fn <- function(){

    print("hello world")

}

I know that typing the function name without the parenthesis will return the function definition, that is:

> temp_fn
function(){

    print("hello world")

}

However, I can't figure out how to store what is printed out into a character object. For example

> store_temp_fn <- as.character(temp_fn)
Error in as.character(temp_fn) : 
  cannot coerce type 'closure' to vector of type 'character'

You can use capture.output() in combination with the function name like this:

temp_fn <- function(){

    print("hello world")

}

temp_fn_string <- cat(paste(capture.output(temp_fn), collapse = "\n"))

> temp_fn_string
function(){

    print("hello world")

}>

Here's another suggestion:

out <- as.character(getAnywhere(temp_fn)$objs)[[1]]
> out
#[1] "function () \n{\n    print(\"hello world\")\n}"
> cat(out)
#function () 
#{
#    print("hello world")
#}
deparse(yourFunction)

Or

paste(deparse(yourFunction), collapse="\n")

if you want it as one big string.

Or, if you want to save it to a file

dput(yourFunction, "yourfile.R")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM