首页 > 解决方案 > Rmarkdown 中的 ifelse 语句和内联注释

问题描述

我正在尝试编写一个简单的行,将行数(即参与者)与先前的数字进行比较,并吐出“低于”、“类似于”或“高于”三个选项之一。

我正在使用 rmarkdown 创建文档,句子看起来像这样

This is `r if(nrow(Data)>1000) { print("higher than")} else if (nrow(Data) <900) { print("lower than")} else { print("similar to")}` previous years response levels.

现在在控制台中它正确吐出

>  |.......................                                               |  33%
  ordinary text without R code
>  |...............................................                       |  67%
>label: unnamed-chunk-1 (with options) 
>List of 1
> $ include: logi FALSE
>  |......................................................................| 100%
>  inline R code fragments
>[1] "lower than"

但在文本文件中,它会打印出句子为

这是往年的反应水平。

为什么 if 语句只在控制台打印而不是内联?

标签: rr-markdown

解决方案


简单的解决方案

你应该这样写:

This is `r if(nrow(Data)>1000) {"higher than"} else if (nrow(Data) <900) {"lower than"} else {"similar to"}` previous years response levels.

你不需要print声明。


为什么打印不起作用

解决方案print不起作用,因为在控制台中print(x)显示并隐形返回。xx

如果您想print在您的解决方案中使用但又想让它发挥作用,则需要(...)在 if 语句周围应用括号,以强制对不可见的返回进行可见性。?invisible如果你不知道这意味着什么,请查看。

这是如何获得保留该print功能的预期结果:

This is `r (if(nrow(Data)>1000) {print("higher than")} else if (nrow(Data) <900) {print("lower than")} else {print("similar to")})` previous years response levels.


可重现的例子

---
title: "Untitled"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Test

```{r}
Data <- data.frame(a = 1:1100)
```

This is `r if(nrow(Data)>1000) {"higher than"} else if (nrow(Data) <900) {"lower than"} else {"similar to"}` previous years response levels.

```{r}
Data <- data.frame(a = 1:800)
```

This is `r if(nrow(Data)>1000) {"higher than"} else if (nrow(Data) <900) {"lower than"} else {"similar to"}` previous years response levels.

```{r}
Data <- data.frame(a = 1:950)
```

This is `r if(nrow(Data)>1000) {"higher than"} else if (nrow(Data) <900) {"lower than"} else {"similar to"}` previous years response levels.

推荐阅读