How can I make inline r script visible in RMarkdown report?

Suppose the command is not important enough to have it on a separate line. But I still want it to be visible by the result, I know that in R Markdown there is ` r inlinestr` , but I can not go echo=T to it. I want the result to be something like this:

enter image description here

+5
source share
2 answers

You can use the return outputs, which will give you a monospace font, but do not obscure the gray background:

f. There is `sum (is.na (df $ Height)) =` `r sum (is.na (df $ Height))` Missing heights.

+3
source

I just ran into this question, which I tried to answer about two years ago, and thought about how to get the code and its evaluated output in one built-in statement. We just need a helper function. The following is an example. The code is entered as a text string, and the function returns both the code and the result of the code evaluation:

 --- title: "RMarkdown teaching demo" author: "whoever" output: pdf_document --- ```{r} fnc = function(expr) { paste(expr, " = ", eval(parse(text=expr))) } # Add some missing values iris$Sepal.Length[c(3,5,10)] = NA ``` f. There are `r fnc("sum(is.na(iris$Sepal.Length))")` missing height values. 

Below is the result.


enter image description here


This works, but there are two problems. Firstly, the code is not in a monospace font. Secondly, the code is not highlighted in gray.

I thought I could get a monospace font with the latex tag \texttt{} .

 ```{r} fnc = function(expr) { paste("\\texttt{", expr, " = ", eval(parse(text=expr)), "}", sep="") } ``` 

It seems that it returns the desired line when interactively launched ( "\\texttt{sum(is.na(iris$Sepal.Length)) = 3}" ), but when trying to knit the document produces the following error:

 ! Extra }, or forgotten $. <recently read> \egroup l.163 ...texttt{sum(is.na(iris$Sepal.Length)) = 3} 

It seemed to me that I can highlight the shortcut with the \hl{} tag (which also requires \usepackage{color, soul} in the latex header):

 ```{r} fnc = function(expr) { paste("\\hl{", expr, " = ", eval(parse(text=expr)), "}", sep="") } ``` 

However, again this causes an error:

 ! Argument of \ SOUL@addmath has an extra }. <inserted text> \par l.161 ...re \hl{sum(is.na(iris$Sepal.Length)) = 3} 

Both texttt{} and \hl{} work without problems when used with plain text inside an rmarkdown document.

So, I'm not sure how to get a monospaced font or selected text, but at least it takes a step towards code + evaluated code from one built-in R operator. I hope someone with more knowledge of language calculation and latex release markup, can give more information on how to make it work as you wish.

+1
source

Source: https://habr.com/ru/post/1243523/


All Articles