【问题标题】:Getting objects in a situation where their name matters在名称很重要的情况下获取对象
【发布时间】:2011-07-28 13:24:19
【问题描述】:

我有一个想要为其制作文档的函数列表。我的问题不是关于如何做到这一点,而是提供了一个我很好奇的方便示例。

prompt 将函数和字符串作为参数,并将该函数的帮助文件写入由字符串路径表示的文件。在循环文件时,使用 prompt(f,filename=...) 不起作用,因为 f 是字符类型。我试过get(f),它把函数拉出来就好了,但没有提供足够的信息来使用(见下文)。那么如何强制一个字符元素返回整个对象而不仅仅是它命名的函数呢?

files <- c("current.market","current.portfolio.bond","fund","genAccount","genHistory.market","history.market","maRketSim.version","summary.vasicek.discrete","vasicek.discrete")
for(f in files) {
  prompt( get(f), filename=paste("c:/myproject/man/",f,".Rd",sep="") )
}
Error in prompt.default(get(f), filename = paste("F:/Documents/R-projects/maRketSim/man/",  : 
  cannot determine a usable name

【问题讨论】:

    标签: r evaluation


    【解决方案1】:

    ?prompt 告诉我们

    Arguments:
    
      object: an R object, typically a function for the default method.
              Can be ‘missing’ when ‘name’ is specified.
    

    所以我认为prompt() 已经做了你想要的:

    > prompt(name = "print", filename = "print.Rd")
    Created file named 'print.Rd'.
    Edit the file and move it to the appropriate directory.
    

    生成相关的 Rd 文件:

    > writeLines(readLines("~/print.Rd"))
    \name{print}
    \alias{print}
    %- Also NEED an '\alias' for EACH other topic documented here.
    \title{
    %%  ~~function to do ... ~~
    }
    \description{
    %%  ~~ A concise (1-5 lines) description of what the function does. ~~
    }
    \usage{
    print(x, ...)
    }
    %- maybe also 'usage' for other objects documented here.
    \arguments{
      \item{x}{
    %%     ~~Describe \code{x} here~~
    ....
    

    我应该补充一点,get("foo") 确实返回实际函数,这正是 prompt() 的编码方式,它不能与 @987654329 返回的匿名函数一起使用@。

    【讨论】:

    • 谢谢加文。我刚刚意识到该提示采用 ,name 参数。但我希望有一些更通用的东西:如何获取名称信息完整的对象。我什至不确定函数的名称信息存储在哪里。查看getS3method("prompt","default"),看起来substitute 用于返回解析树,然后检查它是否是带有is.name 的名称。但我怀疑g &lt;- get(f); name(g) &lt;- f 不仅不起作用,而且在概念上是错误的。
    • name 只是通过名称而不是具有该名称的对象的内容来引用 R 对象的方式。如何进行实际上取决于您想做什么。您可以包装prompt() 并对f 进行各种操作以获得您想要的。但我不清楚你一般想做什么。
    • 这个问题可能是相关的:Getting the object name for S3 print method failing
    • 好吧,也许我会尝试找到另一个例子来说明一般情况下它会有所帮助。基本上我正在尝试更多地了解编程语言,所以每次我遇到getevalassignbquote 等问题时​​我都会尝试更多地考虑它们如果它们不是最简单的解决方案。
    • @Aaron Your 和 Joris 在链接 Q 中的回答很好地一针见血。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 2013-05-19
    • 2023-04-02
    • 2017-06-07
    • 2012-05-23
    • 1970-01-01
    相关资源
    最近更新 更多