Search code examples
rr-markdown

Evaluate inline R code in string for markdown output


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>

Solution

  • 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))