简体   繁体   English

将函数定义存储为字符对象

[英]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: 您可以将capture.output()与函数名称结合使用,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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