r - 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 语句只在控制台打印而不是内联?
解决方案
简单的解决方案
你应该这样写:
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)
显示并隐形返回。x
x
如果您想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.
推荐阅读
- javascript - 如何从“选择”标签中选择除隐藏值之外的值?
- angular6 - 我们可以导航到 Angular 6 中拦截器中的某个 URL 吗?
- python - 我在数据清理方面遇到了一些问题
- node.js - 在 Mongo shell 中访问我的用户详细信息的命令是什么?
- firebase - 如何为firebase项目设置子域,该域已在谷歌注册
- swift - Swift 4 - 检查图像是否高清
- django - 使用 axios 从 React/Redux 前端将文件上传到 Django 时出现问题
- java - web.xml 中 cookie 安全标志的动态值
- python - Django Python - 本月和过去 6 个月的查询计数
- python - Python urllib 'ascii' 编解码器无法在位置 5 编码字符 '\u2757':序数不在范围内(128)