Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate inline R code in string for markdown output

Tags:

r

r-markdown

Given the following R code, how can I first evaluate the inline R code inside the string and next parse it for markdown?

foo <- 6
bar <- "kg"
str <- "The *value* is `r foo` DKK per `r bar`"
# str <- eval_inline(str)   # missing a function to evaluate the inline r  
# (I guess that the knitr package has a solution somewhere in the code)
cat(markdown::mark_html(str))
# output wanted for the <p> tag: <p>The <em>value</em> is 6 DKK per kg</p>
# and not <p>The <em>value</em> is <code>r foo</code> DKK per <code>r bar</code></p>
like image 953
Relund Avatar asked Aug 06 '26 04:08

Relund


1 Answers

I found the solution as

foo <- 6
bar <- "kg"
str <- "The *value* is `r foo` DKK per `r bar`"

# Function to evaluate inline R code within a string
eval_inline <- function(str) {
   file <- textConnection(str)
   result <- knitr::knit_expand(file, delim = c("`r ", "`"))
   close(file)
   return(result)
}
evaluated_str <- eval_inline(str)
cat(markdown::mark_html(evaluated_str))
like image 192
Relund Avatar answered Aug 08 '26 18:08

Relund