【问题标题】:Convert function objects to strings/text? [duplicate]将函数对象转换为字符串/文本? [复制]
【发布时间】:2020-09-27 05:08:24
【问题描述】:

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

谢谢!

【问题讨论】:

  • 看到这实际上并不完全是重复的,因为用户希望将 cmets 保留在函数中。但不知道如何重新打开。

标签: r string function text tostring


【解决方案1】:

我支持 dput:

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

dput(sqfxn)

【讨论】:

  • 试过 dput - 问题是生成的对象仍然是一个函数。不过谢谢你:)
【解决方案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)
# }

【讨论】:

  • 哦,好吧,试试这个。谢谢!
【解决方案3】:

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

body(sqfxn)

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    相关资源
    最近更新 更多