R Markdown script does not always display result - r

I have a problem with a RMD script. It runs. Once. After that, I get partial results.
The code:
---
title: "Dashboard"
output:
flexdashboard::flex_dashboard:
runtime: shiny
---
```{r global, include=FALSE}
library(dplyr)
library(flexdashboard)
Name=c('Test1', 'Test1', 'Test2')
Number = c(8, 9, 7)
zt <- data.frame(Name, Number)
PersonList <- sort(unique(zt$Name))
```
Selections {.sidebar}
===============================
```{r}
## The shiny part
selectInput("PersonSel", "Person: ", PersonList, selected = 'Test1')
```
Tab 1
======================================================================
Row {.tabset}
-----------------------------------------------------------------------
### Table
```{r}
renderTable({
cqi <- zt %>%
na.omit() %>%
filter(Name %in% input$PersonSel) %>%
group_by(Number) %>%
summarise(Count = n())
}, align='l')
```
Result:
When I run the script again, I get this:
In R Studio I see this:
But only this - it doesn't continue.
The only way to get it working again is to edit the script. Add a space or whatever.
Is seems very strange behavior. What can be the problem (and solution) here?

Related

Numbered gt tables in rmarkdown

I'd like to number my tables made with the gt package in rmarkdown rendered pdf.
What I've tried
In a markdown doc, defining a function f that increments a variable every time it is called:
---
title: "."
output: bookdown::pdf_document2
---
```{r}
library(gt)
.i <- 1
f <- function() {.i <<- .i + 1 ; as.character(.i)}
```
```{r numbered_kable}
knitr::kable(head(mtcars,2), caption = "bla")|> kableExtra::kable_styling(latex_options = "HOLD_position")
```
```{r numbered_but_ugly}
mtcars |> head(2) |>
gt() |>
tab_header(
glue::glue("{f()} blabla2")
)
```
Which works, but is a bit involved if both figures and tables need to be numbered.
Question
What is the best way to number figures and tables in using the gt package?
There is a cross-referencing version that seems to be working
devtools::install_github("rstudio/gt", ref="eff3be7384365a44459691e49b9b740420cd0851")
-markdown code
---
title: "."
output: bookdown::pdf_document2
---
```{r}
library(gt)
library(dplyr)
```
```{r numbered_gt}
mtcars %>%
head(2) %>%
gt() %>%
tab_header(title="blabla2",
label="tab:tab1")
```
-output

r - flexdashboard isolate table for child Rmd

I'm trying to incorporate an Rmd I have been using into a flexdashboard. I'm curious if it is possible to isolate an uploaded file and use it as-is rather than writing a bunch of reactive functions. If this is my template, is it possible to get a static object named df that the child document can go ahead and run with?
---
title: "help"
runtime: shiny
output:
flexdashboard::flex_dashboard:
orientation: columns
---
```{r}
fileInput("data", "select data")
df <- isolate(input$data)
```
```{r, child="some_code.Rmd"}
```
My real example does something completely different but let's say some_code.Rmd looks like this:
---
title: "some code"
output: html_document
---
```{r packages, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE)
library(tidyverse)
```
The data looks like this:
```{r}
as_tibble(df)
```
The numeric data can be summarized with the following means
```{r}
df |>
summarise(across(where(is.numeric), mean)) |>
gather()
```
This ended up working:
knitr::knit() + markdown::markdownToHTML() + HTML() ---> renderUI()
---
title: "help"
runtime: shiny
output:
flexdashboard::flex_dashboard:
orientation: rows
---
Sidebar {.sidebar}
==============================================
```{r file-input}
fileInput("data", "select data")
```
Row
==============================================
```{r knit-child}
observeEvent(input$data, {
df <- isolate(read.csv(input$data$datapath))
new_env <- list2env(list(df = df))
output$res <- renderUI({
knitr::knit("some_code.Rmd", quiet = TRUE, envir = new_env) |>
markdown::markdownToHTML() |>
HTML()
})
})
uiOutput("res")
```

SQLite and Shiny/flexdashboard: Cannot embed a reactiveValues() object in a SQL query

I am trying to filter a sqlite3 database and print/plot the resulting data. E.g. the nycflights13::weather data. But in a flexdashboard environment it complains of not being able to embed a reactive object in an SQL query. Does that mean that I can't use SQLite with flexdashboard?
---
title: "Untitled"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(DBI)
library(dplyr)
library(tidyr)
library(pool)
con <- dbConnect(RSQLite::SQLite(), dbdir=":memory:")
DBI::dbWriteTable(con, "weather", nycflights13::weather)
bigdf<-tbl(con, "weather")
```
Column {.sidebar}
----------------------------
```{r}
selectInput("year", label = "year :",
choices = c(2012,2013,2010))
```
Column {data-width=650}
-----------------------------------------------------------------------
### Chart A
```{r}
a<-reactive({
a<-
bigdf%>%
filter(origin=="EWR" & year == as.integer(input$year)) %>%
head(25)%>%
collect()
})
renderTable(a())
```
Column {data-width=350}
-----------------------------------------------------------------------
### Chart B
```{r}
reactive({
plot(a()$year,a()$wind_speed)
})
```
I tweaked the code a bit to use the !! fix as suggested as well as make the b plot a reactive object that can then be rendered with a call to renderPlot.
title: "Untitled"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(DBI)
library(dplyr)
library(tidyr)
library(pool)
con <- dbConnect(RSQLite::SQLite(), dbdir=":memory:")
DBI::dbWriteTable(con, "weather", nycflights13::weather)
bigdf<-tbl(con, "weather")
```
Column {.sidebar}
----------------------------
```{r}
selectInput("year", label = "year :",choices = c(2013,2012,2010),selected = 2013)
```
Column {data-width=650}
-----------------------------------------------------------------------
### Chart A
```{r}
a <- reactive({
a <-
bigdf %>%
filter(origin=="EWR" & year == as.integer(!!input$year)) %>%
head(25) %>%
collect()
a # make sure to return something
})
renderTable(a())
```
Column {data-width=350}
-----------------------------------------------------------------------
### Chart B
```{r}
b <- reactive({ # make the plot a reactive object
plot(a()$year, a()$wind_speed)
})
renderPlot(b()) # then render it
```
Result shown here.

How to print PDF tables created with kable in landscape layout with a caption?

Context: I am knitting an Rmarkdown report mixing landscape and portrait layouts. I use the technique described here: https://stackoverflow.com/a/41945462/10264278.
Problem: there is an unexpected table layout problem. when the table is made using kableExtra::kable() it does not follow the expected orientationif a caption is filled in kable(caption =...).
Reproducible example:
---
output: pdf_document
header-includes:
- \usepackage{pdflscape}
- \newcommand{\blandscape}{\begin{landscape}}
- \newcommand{\elandscape}{\end{landscape}}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo=FALSE, warning=FALSE, comment=FALSE, message=FALSE)
library(dplyr)
library(kableExtra)
```
\blandscape
```{r}
mtcars # displays properly
mtcars %>% kable(caption = "test", digits = 2) # the table follows the landscape layout and does not remains "still"/"horizontal"
```
\elandscape
The output:
Table on the left (mtcars) is displayed as expected. But, if I use kable() the table "turns with the page" witch is not expected.
EDIT:
I am aware that kableExtra::landscape() exists. But this function creates a new page for each table. Here I have many few-rows tables that are very wide. Thus I do not want to have a single table per page.
Example:
```{r}
head(mtcars, 5) %>% kable(caption = "test", digits = 2) %>% landscape(margin = NULL)
head(mtcars, 5) %>% kable(caption = "test", digits = 2) %>% landscape(margin = NULL)
```
Output:
EDIT 2:
This problem occurs only if a caption is specified in kable(caption = ...).
Example:
\blandscape
```{r}
mtcars # displays properly
mtcars %>% kable(digits = 2) # the table follows the landscape layout and does not remains "still"/"horizontal"
```
\elandscape
Output:

Printing any number of dataframes stored in list as paged tables in rmarkdown

I often want to print out the dataframes contained in a list as paged tables in my rmarkdown documents. Calling each dataframe individually renders the desired ouptut if the right df_print option is selected. However, the point of having a list is that the number of dataframes varies depending on the parameters passed to the rmarkdown document; so that's no real solution.
Based on Vincent Guyader's answer to this question and on this example of rmarkdown::paged_table, I've tried to do the following without success.
Is there a way to achieve this at all? I'd be happy to use any package that supports pagination remotely resembling the df_print option.
---
title: "Printing paged tables from a list of dataframes in Rmarkdown"
output:
html_document:
df_print: paged
---
```{r}
library(DT)
library(rmarkdown)
library(purrr)
library(knitr)
df_list <- list("cars" = mtcars, "flowers" = iris)
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, results='asis')
```
### Desired output but impossible to generalise
```{r}
df_list[["cars"]]
```
```{r}
df_list[["flowers"]]
```
### datatable shows as blanks on the page
```{r}
map(df_list, ~DT::datatable(.x) %>%
htmltools::tagList() %>%
print())
```
### rmarkdown outputs dataframe contents as one very long string
```{r}
map(df_list, rmarkdown::paged_table)
```
The issue is that the JS dependencies needed to render the Datatable are not included in the HTML output. A workaround which I borrowed from here is to add a code chunk
```{r init-step, include=FALSE}
DT::datatable(mtcars)
```
outside of the loop or map statement which ensures that the JS dependencies are included. Also, I would recommend to switch to purrr::walk as using map has the effect that the tables are plotted twice.
---
title: "Printing paged tables from a list of dataframes in Rmarkdown"
output:
html_document:
df_print: paged
---
```{r}
library(DT)
library(rmarkdown)
library(purrr)
library(knitr)
df_list <- list("cars" = mtcars, "flowers" = iris)
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, results='asis')
```
### Desired output but impossible to generalise
```{r}
df_list[["cars"]]
```
```{r}
df_list[["flowers"]]
```
### datatable shows as blanks on the page
```{r init-step, include=FALSE}
DT::datatable(mtcars)
```
```{r}
walk(df_list, ~DT::datatable(.x) %>%
htmltools::tagList() %>%
print())
```
When using results='asis' argument, the renderer (here DT) has to be initialized once before being applied on a asis list.
This seems to be a general problem, see here with leaflet, and here with Highcharter.
The answer to this general question has been given here.
In this case:
---
title: "Printing paged tables from a list of dataframes in Rmarkdown"
output:
html_document:
df_print: paged
---
```{r,}
library(DT)
library(rmarkdown)
library(purrr)
library(knitr)
df_list <- list("cars" = mtcars, "flowers" = iris)
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, results='asis')
# initialize the renderer
data.frame() %>%
DT::datatable() %>%
knitr::knit_print() %>%
attr('knit_meta') %>%
knitr::knit_meta_add() %>%
invisible()
```
```{r , results='asis'}
#Remove already printed element and print the rest
df_list[[1]] <- NULL
map(df_list, ~DT::datatable(.x) %>%
htmltools::tagList() %>%
print())
```

Resources