Search code examples
rr-markdownrnotebook

Elegant way to embed statistic contingently in r markdown/notebook [r]


I want to embed statistics in an rMarkdown/notebook depending on whether an if test is passed.

I haven't found a question that addresses this in SO, but apologies if I've overlooked it.

Based on this link I found how to use an if statement to determine what text goes in, I can simply do:

``` {r}
this_p_value = .03


```
`r if(this_p_value<.05){"this is significant"} else {"this is not significant"}`

If I want to report the p-value I can do:

this_p_value is a significant as p= `r this_p_value`

I've got an answer that shows how you do both, but I imagine there may be a more elegant way than my posted solution (or at least a few alternatives). Apologies again if I've overlooked an SO question addressing this.


Solution

  • Something I've played with, but never fully developed, is a set of functions to make these kinds of constructs a little more manageable in markdown. In this case, toggle_text

    toggle_text <- function(condition, true, false)
    {
      coll <- checkmate::makeAssertCollection()
    
      checkmate::assert_logical(x = condition,
                                len = 1,
                                add = coll)
    
      checkmate::assert_character(x = true,
                                  len = 1,
                                  add = coll)
    
      checkmate::assert_character(x = false,
                                  len = 1,
                                  add = coll)
    
      checkmate::reportAssertions(coll)
    
      if (condition) true
      else false
    }
    

    Which can be used as

    ---
    title: "Untitled"
    output: html_document
    ---
    
    ```{r}
    install.packages("checkmate") #comment out if installed
    library(checkmate)
    
    toggle_text <- function(condition, true, false)
    {
      coll <- checkmate::makeAssertCollection()
    
      checkmate::assert_logical(x = condition,
                                len = 1,
                                add = coll)
    
      checkmate::assert_character(x = true,
                                  len = 1,
                                  add = coll)
    
      checkmate::assert_character(x = false,
                                  len = 1,
                                  add = coll)
    
      checkmate::reportAssertions(coll)
    
      if (condition) true
      else false
    }
    
    this_p_value = 0.03
    ```
    
    This is `r toggle_text(this_p_value <= 0.05, "", "not")` significant as p = `r this_p_value`.
    
    
    ```{r}
    this_p_value = 0.07
    ```
    
    This is `r toggle_text(this_p_value <= 0.05, "", "not")` significant as p = `r this_p_value`.