簡體   English   中英

將函數定義存儲為字符對象

[英]Store function definition as a character object

采取以下示例功能

temp_fn <- function(){

    print("hello world")

}

我知道鍵入不帶括號的函數名稱將返回函數定義,即:

> temp_fn
function(){

    print("hello world")

}

但是,我不知道如何將打印出的內容存儲到角色對象中。 例如

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

您可以將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")

}>

這是另一個建議:

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)

要么

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

如果您希望將其作為一個大字符串。

或者,如果您要將其保存到文件中

dput(yourFunction, "yourfile.R")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM