我正在尝试使用 Rmarkdown 生成自动 html 输出。有些报告仅包含 2022 年的数据,有些包含 2017 年和 2022 年的数据。
我想根据该诊所可用的数据有条件地打印文本。
我最初创建一个数据集,如果没有观察结果,每个变量将打印 0:
data_from_2017 <- as.data.frame(colSums(!is.na(clinic_subset17))) %>%
t() %>%
as.data.frame()
然后这是我正在使用的内联代码:
`r
if (data_from_2017$lifesatisfaction == 0) {
Their current life satisfaction was rated on a scale of 1-10 (with 10 representing the highest satisfaction). The average life satisfaction score for your clinic was `r life_sat` in 2022.
} else {
Their current life satisfaction was rated on a scale of 1-10 (with 10 representing the highest satisfaction). The average life satisfaction score for your clinic was `r life_sat17` in 2017 and `r life_sat` in 2022.
} `
但是,它无法解析 - 我做错了什么?
这是使用
cat()
、块选项 results='asis'
和自定义辅助函数来实现所需结果的一种可能选项:
---
title: "Untitled"
output: html_document
date: "2023-12-04"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
data_from_2017 <- data.frame(
lifesatisfaction = 0
)
life_sat <- 8
life_sat17 <- 6
```
```{r}
life_sat_helper <- function() {
sentence <- paste(
"Their current life satisfaction was rated on a scale of 1-10 (with 10 representing the highest satisfaction).",
"The average life satisfaction score for your clinic was"
)
if (data_from_2017$lifesatisfaction == 0) {
cat(sentence, life_sat, "in 2022.\n")
} else {
cat(sentence, life_sat17, "in 2017 and", life_sat, "in 2022.\n")
}
}
```
```{r, results='asis'}
life_sat_helper()
```
```{r}
data_from_2017 <- data.frame(
lifesatisfaction = 1
)
```
```{r results='asis'}
life_sat_helper()
```