有人将R中的函数转换为字符串或文本对象吗?
假设一个简单的平方函数,我想转换为文本文件:
sqfxn <- function(x){
# Get square of x
# Expect:
# > sqfxn(2)
# > 4
output <- x^2
return(output)
}
是否存在将sqfxn()
转换为字符串对象的函数?
fxn_to_text <- function(x){
# convert function x to text
}
这将导致:
> txt_fxn <- fxn_to_txt(sqfxn)
> print(txt_fxn)
> "function(x){
# Get square of x
# Expect:
# > sqfxn(2)
# > 4
output <- x^2
return(output)
}"
谢谢!
使用capture.output()
:
fun <- paste(capture.output(sqfxn), collapse = "\n")
cat(fun)
# function(x){
# # Get square of x
# # Expect:
# # > sqfxn(2)
# # > 4
# output <- x^2
# return(output)
# }
您可以使用body
,顾名思义,它返回函数的主体。
body(sqfxn)
#{
# output <- x^2
# return(output)
#}
但是,这不会捕获在函数内部编写的注释。
我正在为dput加油:
sqfxn <- function(x){
# Get square of x
# Expect:
# > sqfxn(2)
# > 4
output <- x^2
return(output)
}
dput(sqfxn)