RMarkdown - Having The Title (text Heading Before A Table) Be Conditional
I have an R Markdown that is parameterized. Basically, I'm filtering a dataframe by a 'case_id' field and outputting a table of those filtered results. I render the RMarkdown docum
Solution 1:
You can do this by wrapping the table heading in appropriate if statements.
---
title: "My Title"
output:
html_document:
params:
case: case
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
data <- read.csv(text="case_id,event,group,start,end,color,line.color
3,event_1,Project,2020-06-15,2020-10-15,#ffffff,#FF0000
3,event_1,Meetings,2020-07-30,2020-07-30,#ffffff,#0000ff
5,event_1,Meetings,2020-08-30,2020-08-30,#ffffff,#FF0000
5,event_1,Meetings,2020-08-30,2020-08-30,#ffffff,#FF0000
5,event_1,Meetings,2020-08-30,2020-08-30,#ffffff,#FF0000
9,event_1,Meetings,2017-01-15,2017-01-15,#ffffff,#FF0000")
data$case_id <- as.numeric(data$case_id)
param_check <- any(params$case==data$case_id)
if (param_check) {
#Filter PDMP by the selected case
data.filtered <- data %>%
filter(params$case==case_id)
data.filtered <- data.filtered %>%
filter(!is.na(start)&!is.na(end))
pdmp_numRows <- nrow(data.filtered)
}
```
`r if (param_check) { if (pdmp_numRows > 0) {"# My Table"} }`
```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
if(param_check) {
if (pdmp_numRows>0) {
#Print table of prescriptions
data.filtered %>%
arrange(start)%>%
kable() %>% kable_styling(bootstrap_options = "striped","condensed", font_size = 12)
}
}
```
Solution 2:
First load your csv into a data.frame then put the title in a chunk that'll get evaluated only when there are cases that have the provided id:
---
title: "My Title"
output:
html_document:
params:
case: case
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
data <- read.csv(text="case_id,event,group,start,end,color,line.color
3,event_1,Project,2020-06-15,2020-10-15,#ffffff,#FF0000
3,event_1,Meetings,2020-07-30,2020-07-30,#ffffff,#0000ff
5,event_1,Meetings,2020-08-30,2020-08-30,#ffffff,#FF0000
5,event_1,Meetings,2020-08-30,2020-08-30,#ffffff,#FF0000
5,event_1,Meetings,2020-08-30,2020-08-30,#ffffff,#FF0000
9,event_1,Meetings,2017-01-15,2017-01-15,#ffffff,#FF0000")
data$case_id <- as.numeric(data$case_id)
```
```{r, eval=any(params$case==data$case_id), results='asis'}
print("## My Table")
```
Post a Comment for "RMarkdown - Having The Title (text Heading Before A Table) Be Conditional"