Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knitr: print text from code block as R markdown

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?

like image 262
matthiash Avatar asked Jun 21 '17 08:06

matthiash


People also ask

Can I convert r script to R Markdown?

In fact, you can take any R script and compile it into a report that includes commentary, source code, and script output. Reports can be compiled to any output format including HTML, PDF, MS Word, and Markdown.

How do I hide code but show output in R Markdown?

include = FALSE prevents code and results from appearing in the finished file. R Markdown still runs the code in the chunk, and the results can be used by other chunks. echo = FALSE prevents code, but not the results from appearing in the finished file.

How do I show output in R Markdown?

If you prefer to use the console by default for all your R Markdown documents (restoring the behavior in previous versions of RStudio), you can make Chunk Output in Console the default: Tools -> Options -> R Markdown -> Show output inline for all R Markdown documents .


1 Answers

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().

like image 148
J_F Avatar answered Sep 25 '22 22:09

J_F