【问题标题】:Different language (esp. Rcpp) not printing output when knitting an Rmarkdown chunk编织 Rmarkdown 块时不同的语言(尤其是 Rcpp)不打印输出
【发布时间】:2017-06-09 12:03:04
【问题描述】:

这在 Rstudio 中有效,我在运行块时直接在文档中获得实时预览。但是,当我将 .Rmd 编​​织到 .html 时,我只会得到代码的回显,而没有输出。

```{r engine='Rcpp'}
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int main() {
  return 4;
}

/*** R
main()
*/
```

如果我用 python 做同样的事情,我会在编织时得到正确的输出:

```{r engine='python'}
print("abc")
```

【问题讨论】:

    标签: r knitr r-markdown rcpp


    【解决方案1】:

    不幸的是,注释标记 (/***R */) 的执行由于您注意到的执行方式而没有被保留。你可以说这是一个rmarkdown 小号;但是,/***R */ 更多地用于在交互式开发过程中嵌入调用。

    另外,使用int main() 是一个很大的禁忌。引用德克的话:

    您不能将 R 上下文放入独立的 main(),因为您需要 R 用于 R 上下文。

    因此,我选择将函数名称更改为 toad()

    为了达到同样的效果并忠实于文学编程,每个部分都应该嵌入到单独的代码块中。也就是说,您必须创建一个 Rcpp 代码块(最好启用缓存)和一个包含实际函数调用的 R 代码块。

    例如

    ---
    title: Test Doc
    author: JJB
    date: 6/9/2017
    output: html_document
    ---
    
    
    ```{Rcpp hpc-code, cache = TRUE}
    #include <Rcpp.h>
    using namespace Rcpp;
    
    // [[Rcpp::export]]
    int toad() {
      return 4;
    }
    ```
    
    ```{r interactive-output}
    toad()
    ```
    

    【讨论】:

    • +1 帮助我解决类似问题。显然,在 {Rcpp cache = TRUE} 块中编写 C++ 函数比使用 {r name, engine='Rcpp'} 标题块然后在调用该函数的另一个 R 块中引用 name 更好,并且更干净。
    猜你喜欢
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多