在r降价/笔记本中意外嵌入统计信息的优雅方式[r]
我想根据if测试是否通过,在rMarkdown/笔记本中嵌入统计信息 我在SO中没有找到一个可以解决这个问题的问题,但如果我忽略了它,请道歉 根据我发现的如何使用if语句来确定输入的文本,我可以简单地执行以下操作:在r降价/笔记本中意外嵌入统计信息的优雅方式[r],r,r-markdown,rnotebook,R,R Markdown,Rnotebook,我想根据if测试是否通过,在rMarkdown/笔记本中嵌入统计信息 我在SO中没有找到一个可以解决这个问题的问题,但如果我忽略了它,请道歉 根据我发现的如何使用if语句来确定输入的文本,我可以简单地执行以下操作: ``` {r} this_p_value = .03 ``` `r if(this_p_value<.05){"this is significant"} else {"this is not significant"}` 我已经得到了一个答案,说明了你们是如何做到这两个
``` {r}
this_p_value = .03
```
`r if(this_p_value<.05){"this is significant"} else {"this is not significant"}`
我已经得到了一个答案,说明了你们是如何做到这两个方面的,但我想可能有一个比我发布的解决方案更优雅的方法(或者至少有一些替代方案)。如果我忽略了一个解决此问题的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"}`
`{r}
该值=0.03
```
`r if(这个值我曾经玩过但从未完全开发过的东西,是一组函数,可以使这些类型的构造在降价时更易于管理。在这种情况下,toggle\u 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
}
toggle\u text你看过post了吗?@erocoar-这篇文章就是我获取if语句的方式,但它似乎不利于将r定义的变量嵌入到输出中。我编辑了我的问题以突出显示该问题。一旦你加载了函数,我可以想象这会使手稿比使用粘贴更容易阅读。我当然,有一些方法可以使用空白使其更具可读性,但实际上我还没有充分使用它来开发任何使用它的经验。当我尝试运行它时,我需要安装软件包“checkmate”,所以编辑了你的代码来包含它。但是它已经很好地工作了!事实上,对不起,我想我遗漏了一些东西。什么时候你的函数会比if([test]){[output 1]}else{[output 2]}更优化?我不是说它不是,只是想我还不明白为什么。它不是。它是一个简化代码创建过程的模板。它最适合包含短字符串。如果您希望包含更长的字符串(段落)这可能不是正确的方法。我只是觉得toggle_text
比原始的if-else
结构更能描述我的目标。
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`.