Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In-line R expression returns incorrect value

If the R code in Rmd file reuses the same variable name, the inline r expressions seem to return the last value of this variable regardless of the location of the inline expression. Is there away to avoid this behavior except for making sure the same variable name is not reused in different parts of the document?

The reproducible example

---
title: "R Notebook"
output: html_notebook
---


```{r}
df <- cars
nrow(df)
```

The dataset has `r nrow(df)` rows.


```{r}
df <- iris
nrow(df)
```

The dataset has `r nrow(df)` rows.

This produces the following output

enter image description here

I am using: R version 3.3.2 (2016-10-31) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 7 x64 (build 7601) Service Pack 1

rmarkdown_1.4 knitr_1.15.1

like image 489
Sasha Avatar asked Mar 25 '17 18:03

Sasha


2 Answers

The problem is that in your header, you are "previewing" your file, which does not actually run your code from scratch. You have to knit it to HTML to have it run so that your in-line code is correct.

Problem Header

---
title: "R Notebook"
output: html_notebook
---

Solution Header

---
title: "R Notebook"
output: 
    html_document: default
    html_notebook: default
---

Other Notes

The previous solution has two problems. First, from the RMarkdown documentation, "Inline expressions do not take knitr options" (see end of http://rmarkdown.rstudio.com/lesson-4.html)

Second, the previous answer's YAML is not formatted properly forcing RStudio to actually knit the file. The proper formatting would generate the same problem you are having

---
title: "R Notebook"
output: 
    html_notebook: default
---
like image 177
Mallick Hossain Avatar answered Oct 17 '22 20:10

Mallick Hossain


At the beginning, we can specify cache = TRUE

---
title: "R Notebook"

output: 
html_notebook: default


---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(cache=TRUE)
```


```{r}
df <- cars
nrow(df)
```

enter image description here

like image 2
akrun Avatar answered Oct 17 '22 19:10

akrun