N Stenfors N Stenfors - 1 month ago 6
R Question

R Markdown inline code not executed

I have an inline code enclosed with single backticks on a single line.
However,

The cohort had

r echo = FALSE load("../data/cohort.rda") nrow(cohort)
subjects.

is not executed and thus gives me this output in html and pdf:

The cohort had
r echo = FALSE load("../data/cohort.rda") nrow(cohort)
subjects.

I want this output: The cohort had
477
subjects.


When I exclude
echo=FALSE
, I get this message:


Quitting from lines 33-35 (Manuscript.Rmd)
Error in base::parse(text = code, srcfile = NULL) :
1:25: unexpected symbol
1: load("../data/cohort.rda") nrow
^

Calls: ... inline_exec -> withVisible -> eval -> parse_only ->
Execution halted

Answer

The inline R code needs to be a single R statement, which you can achieve by surrounding the entire code chunk with brackets {} and separating commands with semicolons. I saved a 3-row data frame named tmp to file tmp.rda, rendered an Rmd file with this line

There are `r {load("tmp.rda"); nrow(tmp)}` observations

and got the expected output.