Knitr: print text from code block as R markdown

2020-06-12 03:11发布

I have the following R Markdown document:

---
title: "Test"
output: html_document
---

```{r cars, echo=FALSE}
myCondition <- TRUE
if(myCondition) {
  print("## Car Summary")
}
summary(cars)
```

When I Knit it to HTML, the "Car Summary" header is rendered in "terminal-like" monospaced font as this:

## [1] "## Car Summary"

But I want it rendered as a header. How do I achieve this?

1条回答
做自己的国王
2楼-- · 2020-06-12 03:43

This should work for you:

```{r cars, echo=FALSE, results='asis'}
myCondition <- TRUE
if(myCondition) {
  cat("## Car Summary")
}
```

```{r, echo=FALSE}
summary(cars)
```

Note that the option results = 'asis' is important to print the header. Also note that print() will not work, but cat().

查看更多
登录 后发表回答