在 r markdown/notebook [r] 中偶然嵌入统计信息的优雅方式

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

我想根据是否通过 if 测试将统计信息嵌入 rMarkdown/notebook。

我没有在 SO 中找到解决这个问题的问题,但如果我忽略了它,我深表歉意。

基于 this link 我发现了如何使用 if 语句来确定要输入的文本,我可以简单地执行以下操作:

``` {r}
this_p_value = .03


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

如果我想报告 p 值,我可以这样做:

this_p_value is a significant as p= `r this_p_value`

我得到了一个答案,说明了你如何做到这两个,但我想可能有比我发布的解决方案(或至少有几个替代方案)更优雅的方法。如果我忽略了解决此问题的 SO 问题,再次道歉。

所以我在写这道题的时候想到的解决办法是:

``` {r}
this_p_value = .03

```

`r if(this_p_value<.05){paste(" this is significant as p=",this_p_value,". [Rest of writeup here]",sep='')} else {"this is not significant"}`

但是使用 "paste" 有什么替代方法吗?

我玩过但从未完全开发过的东西是一组函数,可以使这些类型的构造在 markdown 中更易于管理。在这种情况下,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
}

可以用作

---
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`.