【问题标题】:How to include an external code file in rmakdown to output in pdf with sintax highlight如何在 r markdown 中包含外部代码文件以使用语法突出显示以 pdf 格式输出
【发布时间】:2020-05-12 19:30:00
【问题描述】:

我的问题来自this one。但是,不同的是我的输出是 PDF。

我有一个C++ 代码保存在一个外部文件中。我想将它打印成带有语法高亮的 r markdown PDF。

我的example.cpp 代码,实际上是TMB 代码:

// Fitting Bivariate Gaussian distribution.
#include <TMB.hpp>
template<class Type>
Type objective_function<Type>::operator() ()
{
  using namespace density;
  DATA_MATRIX(Y);
  PARAMETER_VECTOR(rho);
  PARAMETER_VECTOR(sigma);
  vector<Type> rho_temp(1);
  rho_temp = rho;
  vector<Type> sigma_temp(2);
  sigma_temp = sigma;
  Type res;
  for(int i = 0; i < 50; i++)
    res += VECSCALE(UNSTRUCTURED_CORR(rho_temp), sigma_temp)(Y.row(i));
  return res;
}

最少的代码:

---
title: "Code to PDF"
output: beamer_presentation
safe-columns: true # enables special latex macros for columns
header-includes:
- \usepackage{listings}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
setwd("/home/guilherme/Google Drive/Mestrado/dissertacao/TMB/Presentation")
```

## Slide1

\lstinputlisting[language=C++]{example.cpp}

结果在幻灯片中:

有没有更好的方法来突出显示?

【问题讨论】:

  • 您可以使用\lstinputlisting[language=C++]{example.cpp} 简化您的命令。也许有一些 ```{latex}... 围绕它。可以发minimal reproducible example 来测试吗?
  • 我只是按照你的建议做了

标签: r latex pdf-generation r-markdown listings


【解决方案1】:

您可以在 Rmarkdown 中运行很多引擎。你可以找到他们here

一般情况:

我的 C++ 存档,我将其命名为“mycpp.cpp”:

# include <iostream>

class Passaro                       // classe base
{
public:
   virtual void MostraNome()
   {
      std::cout << "um passaro";
   }
   virtual ~Passaro() {}
};

class Cisne: public Passaro         // Cisne é um pássaro
{
public:
   void MostraNome()
   {
      std::cout << "um cisne";        // sobrecarrega a função virtual
   }
};

int main()
{
   Passaro* passaro = new Cisne;

   passaro->MostraNome();            // produz na saída "um cisne", e não "um pássaro"

   delete passaro;
}

我的 Rmd 存档:


---
title: "Code to PDF"
output:
  pdf_document
---

# Cats are nicer than dogs

```{Rcpp, code=readLines('mycpp.cpp')}
```

输出:

具体到你的情况,试试这个:

---
title: "Code to PDF"
output: beamer_presentation
safe-columns: true # enables special latex macros for columns
header-includes:
- \usepackage{listings}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
setwd("/home/guilherme/Google Drive/Mestrado/dissertacao/TMB/Presentation")
```

## Slide1

```{Rcpp, eval = FALSE, echo = TRUE, code=readLines('example.cpp')}
```

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 2015-04-14
    • 2022-06-25
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    相关资源
    最近更新 更多