【问题标题】:Reuse r code with knitr in rnw / sweave files在 rnw / sweave 文件中使用 knitr 重用 r 代码
【发布时间】:2018-09-07 00:22:20
【问题描述】:

我正在寻找一种使用 knitr 在乳胶中重用 r 代码的方法。我有多个 Excel 文档,我想在整个论文中以相同的方式导入、分析和绘图。现在,我正在为我拥有的每个 excel 文档制作一个新的 .rnw 文件。这意味着,如果我想更改任何内容,我必须在每个 .rnw 文件中进行更改——这似乎是错误的方法。有没有办法,我可以从父 .rnw 调用一个 .rnw 文件,并为它提供一个 excel 文件名来导入和使用。

【问题讨论】:

    标签: r latex knitr code-reuse rnw


    【解决方案1】:

    是的,有。您可以同时使用 paramsrender 函数来帮助解决这个问题。如果您不熟悉参数,请查看此处params 和此处查看render。我为以下示例编写了 iris 和 mtcars 以使其表现出色。在下面的降价中,我调用了块中的 excel 参数,它是 excel 文件,只打印前 10 行。

    ---
    title: "iris"
    output: pdf_document
    params:
      excel: "G:/iris2.xlsx"
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    ```
    
    
    
    ```{r cars}
    head(xlsx::read.xlsx(params$excel,sheetIndex = 1))
    ```
    

    现在要更改 excel 文件,您可以使用 lapply 和 .R 文件中的渲染函数。

    #create list of excel files
    exldocs <- c("G:/mtcars2.xlsx", "G:/iris2.xlsx")
    
    #call the renders.rmd (above), pass the list of excel files to overwrite the #default param field, output a new pdf (call it whatever you want)  
    lapply(exldocs, function(x){
           rmarkdown::render("G:/renders.Rmd", params = list(excel = x),
                             output_file =paste0(substr(x,1,nchar(x)-4),"pdf")
                               )})
    

    【讨论】:

    • 这是在降价中。我已经用 rnw 写了。有替代方案吗? :) 还是我应该开始使用降价代替
    • 好问题 - 抱歉,我以为你的问题是 rmd。我没有 rnw 解决方案。但是,如果您有兴趣轻松切换到 rmd,请从 knitrknitr::Sweave2knitr() 中查看此功能。也许还可以查看knitr::render_sweave
    【解决方案2】:

    您可以使用knitr::knitenvir 参数,如下所示。这是.Rnw 文件

    % parameterized_reports.Rnw
    \documentclass{article}
    
    \begin{document}
    
    <<>>=
    foo
    @
    
    \end{document}
    

    这里是 R 代码

    tmp <- environment()
    tmp$foo <- "xyz"
    knitr::knit("parameterized_reports.Rnw", envir = tmp, output = "output.tex")
    tools::texi2pdf("output.tex")
    system('open output.pdf')
    

    结果是

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-08
      • 1970-01-01
      相关资源
      最近更新 更多