将函数对象转换为字符串/文本? [重复]

问题描述 投票:0回答:3

有人将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)
  }"

谢谢!

r string function text tostring
3个回答
2
投票

使用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)
# }

0
投票

您可以使用body,顾名思义,它返回函数的主体。

body(sqfxn)

#{
#    output <- x^2
#    return(output)
#}

但是,这不会捕获在函数内部编写的注释。


0
投票

我正在为dput加油:

sqfxn <- function(x){
  # Get square of x
  # Expect: 
  # > sqfxn(2)
  # > 4
  output <- x^2
  return(output)
}

dput(sqfxn)
© www.soinside.com 2019 - 2024. All rights reserved.