【问题标题】:Extracting arguments of an R function to use in knitr提取 R 函数的参数以在 knitr 中使用
【发布时间】:2013-11-21 12:56:39
【问题描述】:

lm函数的参数可以使用:

args(lm)

输出

function (formula, data, subset, weights, na.action, method = "qr", 
    model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, 
    contrasts = NULL, offset, ...) 
NULL

问题

如何获得:

lm (formula, data, subset, weights, na.action, method = "qr", 
    model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, 
    contrasts = NULL, offset, ...) 

Sweaveknitr 中使用每个参数的描述(不是完整的帮助)。谢谢

已编辑

使用@Ananda 提供的 funExtract 函数,我非常接近我想要的结果。这是我的Rnw 文件的代码,带有输出。

\documentclass{article}
\usepackage[T1]{fontenc}

\begin{document}

Arguments for lm

<< label = funExtract, echo = TRUE, results = "hide", tidy = FALSE >>=
funExtract <- function(Function, section = "Usage") {
  A <- deparse(substitute(Function))
  x <- capture.output(tools:::Rd2txt(utils:::.getHelpFile(help(A))))
  B <- grep("^_", x)                    ## section start lines
  x <- gsub("_\b", "", x, fixed = TRUE) ## remove "_\b"
  X <- rep(FALSE, length(x))
  X[B] <- 1
  out <- split(x, cumsum(X))
  out <- out[[which(sapply(out, function(x) 
    grepl(section, x[1], fixed = TRUE)))]]
  cat(out, sep = "\n")
  invisible(out)
}
@

\vspace{0.5cm}\\
funExtract function output
\vspace{0.25cm}\\
<< label = lm-usage, echo = FALSE, results = "asis" >>=
funExtract(lm, section="Usage:")
@

\vspace{0.5cm}\\
args function output
\vspace{0.25cm}\\
<< label = lm-args, echo = FALSE, results = "asis" >>=
args(lm)
@


\end{document}

输出

funExtract 函数输出的问题

  1. 如何将 funExtract 函数的突出显示输出作为其他代码?
  2. 如何从 funExtract 函数输出中删除部分标题?

【问题讨论】:

  • args(lm) 应该仍然可以在 Sweave 或 knitr 中工作。你没有做什么?
  • 你可能想看看formalArgs(lm)formals(lm)sig(lm),最后一个在sig包中。
  • 感谢@AnandaMahto 愿意抽出时间解决第一个问题。恐怕out &lt;- out[-1] 也没有提供预期的结果。
  • this。如果您安装了最新版本的“devtools”,则有一个示例 Rnw 和 Rmd 文件应该可以直接工作。如果不是,请将前几行替换为 helpExtract 函数,也在该页面上。祝你好运。
  • 我有一个单一的解决方案,稍后我将发布它来解决您提到的所有问题。

标签: r knitr sweave


【解决方案1】:

我在 formatR 包中有一个函数 usage(),它捕获函数的参数。现在,您必须使用development version (>= 0.10.3)。

对于knitr,我最近也有一个变化(即请同时测试其开发版本on Github),以便您可以更轻松地使用显示功能:您可以使用新的块选项code 将代码输入到一个块中。

把这两部分放在一起,你就能写出这样的代码块:

<<test, code=formatR::usage(lm), eval=FALSE>>=
@

最近出现这些功能的原因是我自己也碰巧需要它们。我想通过语法高亮显示函数的用法。此解决方案可移植到 knitr 支持的所有文档格式,不限于 Rnw。

【讨论】:

  • 不错的功能。感谢@Yihui 的出色工作。此函数的输出宽度可以通过formatR::usage(FUN=lm, width=50) 之类的东西来控制。 @AnandaMahto 的 helpExtract 函数更通用,因为它可以提取帮助文件的任何部分。
【解决方案2】:

我已经编写了一个函数并将其作为答案发布(如问题本身所述),但对不一致或必须与“markdown”一起使用才能成功使用的要求并不完全满意.经过一点点工作,这是我想出的功能:

helpExtract <- function(Function, section = "Usage", type = "m_code", ...) {
  A <- deparse(substitute(Function))
  x <- capture.output(tools:::Rd2txt(utils:::.getHelpFile(help(A, ...)),
                                     options = list(sectionIndent = 0)))
  B <- grep("^_", x)                    ## section start lines
  x <- gsub("_\b", "", x, fixed = TRUE) ## remove "_\b"
  X <- rep(FALSE, length(x))
  X[B] <- 1
  out <- split(x, cumsum(X))
  out <- out[[which(sapply(out, function(x) 
    grepl(section, x[1], fixed = TRUE)))]][-c(1, 2)]
  while(TRUE) {
    out <- out[-length(out)]
    if (out[length(out)] != "") { break }
  } 

  switch(
    type,
    m_code = c("```r", out, "```"),
    s_code = c("<<>>=", out, "@"),
    m_text = paste("    ", out, collapse = "\n"),
    s_text = c("\\begin{verbatim}", out, "\\end{verbatim}"),
    stop("`type` must be either `m_code`, `s_code`, `m_text`, or `s_text`")
  )
}

相当拗口,而且并不完全干燥......但我想捕捉四个场景,这是我想到的最快的想法。我预计的四种情况是:

  1. 文档类型为 markdown,用户正在提取代码块 (type = "m_code")
  2. 文档类型为 markdown,用户正在提取非代码部分 (type = "m_text")
  3. 文档类型为 Sweave,用户正在提取代码块 (type = "s_code")
  4. 文档类型为 Sweave,用户正在提取非代码部分 (type = "s_text")

该函数提取Rd2txt 的输出。我选择了它而不是其他格式(HTML、LaTeX),以允许我使用单个函数来获得我所追求的内容,而不必创建多个函数。


用法

根据您是创建“Sweave” (.Rnw) 还是“markdown” (.Rmd) 文档,用法会有所不同。

  1. 降价

    将您的代码插入一个看起来像这样的代码块中(也许有一天我会添加不同的方法,但不是现在):

    ```{r, echo=FALSE, results='asis'}
    cat(helpExtract(cor), sep = "\n")
    ```
    
  2. 编织

    假设您正在使用Sexpr{knit_child(.)} 插入应包含在主文档中的“子”文档

    \Sexpr{knit_child(textConnection(helpExtract(cor, type = "s_code")), 
    options = list(tidy = FALSE, eval = FALSE))}
    

我有created a Gist,其中包括函数、示例 Rmd 文件和示例 Rnw 文件。随意在 Stack Overflow 上留下 cmets 和建议(因为 Gist cmets 几乎毫无意义,因为它们不会在发布评论时通知用户)。


如果您尝试从当前未加载的包中引用函数,helpExtract 的用法应该类似于:

helpExtract(gls, package = "nlme")

【讨论】:

  • 我测试了这个新功能。这适用于文档类文章,但在我的机器上使用投影仪失败。为什么不呢?
  • @MYaseen208,我实际上不使用 Sweave 或 Beamer。请随意解构我的函数,看看你是否能找出适合你的方法。
  • @MYaseen208,它对我有用。使用template here 作为起点。如果您使用 type = "s_code" 以外的任何内容,您可能仍然需要调整该功能,因为其他部分的线宽可能不适合 Beamer 幻灯片。
  • 需要修改stats::lmnlme::gls等函数。
  • 您好@AnandaMahto:我有一个与helpExtract 函数有关的问题here
【解决方案3】:

您可以使用Rd_db 从包中获取 Rd 数据。

x <- Rd_db("stats")

从中提取 lm 帮助:

lmhelp <- x[basename(names(x))=="lm.Rd"]

然后使用capture.outputRd2latex获取帮助页面的latex:

lmhelptex <- capture.output(Rd2latex(lmhelp[[1]]))

然后拉出您想要包含在 rnw 文件中的片段:

lmhelptex[do.call(":",as.list(grep("Usage",lmhelptex)))]
[1] "\\begin{Usage}"                                                    
[2] "\\begin{verbatim}"                                                 
[3] "lm(formula, data, subset, weights, na.action,"                     
[4] "   method = \"qr\", model = TRUE, x = FALSE, y = FALSE, qr = TRUE,"
[5] "   singular.ok = TRUE, contrasts = NULL, offset, ...)"             
[6] "\\end{verbatim}"                                                   
[7] "\\end{Usage}"  

lmhelptex[do.call(":",as.list(grep("Arguments",lmhelptex)))]
 [1] "\\begin{Arguments}"                                                                           
 [2] "\\begin{ldescription}"                                                                        
 [3] "\\item[\\code{formula}] an object of class \\code{\"\\LinkA{formula}{formula}\"} (or one that"
 [4] "can be coerced to that class): a symbolic description of the"                                 
 [5] "model to be fitted.  The details of model specification are given"                            
 [6] "under `Details'."                                                                             
 [7] ""                                                                                             
 [8] "\\item[\\code{data}] ...snip...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2021-08-04
    • 2021-05-06
    • 2021-07-22
    • 2021-06-14
    相关资源
    最近更新 更多