Markdown not compiling after first Chunk (stoping when reaching html scrape) - r

Markdown does not compile after the first chunk. I am able to run all the chunk individually and run them all at once. When attempting to Knit to a HTML document, markdown does not compile right at the first chunk and stops. No Errors, No Warnings, etc., and just stops.
I have tried eval = False, which just outputs nothing, I removed several portions of the code and found it is the portion of the scrape of the HTML table. However, works when I run the chunk.
---
title: "Harry Potter Cast"
author: "Ben Tanaka"
date: "5/29/2019"
output:
html_document:
keep_md: yes
---
```{r setup, echo=FALSE, include=FALSE, warning=FALSE,message =FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(xml2)
library(rvest)
library(stringr)
library(tibble)
library(data.table)
library(knitr)
library(kableExtra)
library(dplyr)
library(tidyr)
library(ggplot2)
```
# *Harry Potter Cast*
```{r Harry_Potter}
potter_url <- 'https://www.imdb.com/title/tt1201607/fullcredits?ref_=tt_ql_1'
potter_scrape <- read_html(potter_url)
potter_cast_uf <- {potter_scrape %>% html_nodes("table") %>% .[[3]] %>% html_table()}
potter_cast_df <- potter_cast_uf[,c(2,4)]
setnames(potter_cast_df,old=c("X2","X4"),new=c("Actor","Character"))
str_replace_all(potter_cast_df$Actor, '[\r\n]' , '')
str_replace_all(potter_cast_df$Character, '[\r\n]' , '')
potter_cast_tbl <- as_tibble(potter_cast_df)
{potter_cast_tbl %>% mutate_all(funs(str_replace_all(.,'[\r\n]' , '')))}
potter_cast_tbl <- potter_cast_tbl[-1,]
potter_cast_tbl <- potter_cast_tbl[-92,]
{potter_cast_tbl %>% mutate_all(funs(str_replace_all(.,'Griphook / \n Professor Filius Flitwick' , 'Griphook / Professor Filius Flitwick')))}
{potter_cast_tbl <- potter_cast_tbl %>% separate(Actor,c("Actor_FName","Actor_MName","Actor_LName"))}
potter_cast_tbl$Actor_FName[!is.na(potter_cast_tbl$Actor_LName)]<- paste(potter_cast_tbl$Actor_FName[!is.na(potter_cast_tbl$Actor_LName)],potter_cast_tbl$Actor_MName[!is.na(potter_cast_tbl$Actor_LName)],sep=" ")
potter_cast_tbl$Actor_LName[is.na(potter_cast_tbl$Actor_LName)] <- potter_cast_tbl$Actor_MName[is.na(potter_cast_tbl$Actor_LName)]
potter_cast_tbl<-potter_cast_tbl[,-2]
output_dt <- head(potter_cast_tbl,10)
{output_dt %>% kable() %>% kable_styling()}
```
No Error messages. Just trying to get the markdown html knit output.

Related

Is there a way to export multiple gt tables to a single HTML output

I have a list of many (can be dozens of) tables created with the gt package in R. I would like to export them all as a single HTML file with a little space between each table. Currently, I have been exporting each table individually, reading them into an RMarkdown with the xfun package, and knitting to a single HTML file. I'm curious if there is a method to cut out the intermediate step of saving each table individually and reading into the Rmd.
Example:
library(gt)
library(tidyverse)
tbl_list <- list(mtcar_tbl = mtcars %>% gt(),
iris_tbl = iris %>% gt(),
cars_tbl = cars %>% gt())
purrr::map(seq_along(tbl_list), function(rownum){
htmltools::save_html(html = tbl_list[[rownum]],
file = paste0("test",rownum,".html"))
})
RMarkdown to combine and export tables:
---
title: ""
output: html_document
---
```{r, echo=FALSE,message=FALSE,warning=FALSE}
library(xfun)
```
```{r echo=FALSE}
htmltools::includeHTML("test1.html")
```
<br><br>
```{r echo=FALSE}
htmltools::includeHTML("test2.html")
```
<br><br>
```{r echo=FALSE}
htmltools::includeHTML("test3.html")
```
One option would be to use purrr::walk with chunk option results="asis" to directly print your tables without the intermediate step. To add the line breaks after each table use cat("<br><br>"):
Note: For the reprex I just print the head of each table.
---
title: "Untitled"
output: html_document
date: "2022-09-19"
---
```{r echo=FALSE, results='asis', warning=FALSE, message=FALSE}
library(gt)
library(tidyverse)
tbl_list <- list(mtcar_tbl = mtcars,
iris_tbl = iris,
cars_tbl = cars)
tbl_list <- purrr::map(tbl_list, ~ head(.x) %>% gt() )
purrr::walk(tbl_list, function(x) { print(x); cat("<br><br>") })
```

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

how can I show my "ztable" when I use "knit to HTML" in R?

I am having a problem with my ztable,
I want to knit my Rmarkdown file to HTML but I cannot find a way to display the table I created with ztable:
z=ztable(loucaste) %>% makeHeatmap(palette = "Blues") %>% print(caption="Table 2.)
I tried to set
options(ztable.table="html")
and put this at the beginning as I read somewhere else
output: html_document
header-includes: \usepackage{colortbl}
but it doesn't work when I knit to HTML. My intention was to create a sort of formatting table similar to the ones made on excel and ztable looks like the only way.
Try this minimal Rmd. The key seems to be options(ztable.type = "html") and in the chunk that generates the table, r results='asis'
If that works for you, substitute your code in the appropriate place i.e. ztable(loucaste) %>% makeHeatmap(palette = "Blues") %>% print(caption="Table 2.).
---
title: "ztable"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ztable)
library(magrittr)
options(ztable.type = "html")
```
## R Markdown
```{r results='asis'}
matrix(1:100, nrow = 10) %>%
as.data.frame() %>%
ztable() %>%
makeHeatmap() %>%
print(caption = "table 2")
```

Using R-markdown knitr hooks to custom format tables in HTML reports

I am trying to set up a knitr::knit_hooks() to automatically format data frame output of an R-markdown chunk with kableExtra in my HTML report.
I would like to not repeatedly add the following lines (or any lines) to the end of each chunk of tabulated data:
head(iris) %>%
kable("html") %>%
kable_styling("hover", full_width = FALSE)
I came up with one solution based on this answer that works by evaluating the chunk source (see my answer below that includes some issues that I have with this approach); I'm hoping there might be a better solution using the chunk output.
Here is an example .Rmd with an outline of what I would like to achieve.
---
title: "Untitled"
author: "Paul"
date: "25 September 2018"
output: html_document
---
```{r setup, include = F}
library(dplyr)
library(kableExtra)
library(knitr)
data(iris)
default_source_hook <- knit_hooks$get('source')
knit_hooks$set(
output = function(x, options) {
x %>%
kable("html") %>%
kable_styling("hover", full_width = FALSE)
},
source = function(x, options) {
if(is.null(options$table))
default_source_hook(x, options)
else {
eval(parse(text = x)) %>%
kable("html") %>%
kable_styling("hover", full_width = F)
}}
)
```
Desired chunk input:
```{r test, echo = F}
head(iris)
```
Desired output will look like:
```{r output, echo = F}
head(iris) %>%
kable("html") %>%
kable_styling("hover", full_width = FALSE)
```
Solution using the source chunk output:
```{r table_format, results = "hide", table = T, eval = F}
head(iris)
```
Thank you.
If using knit hooks is not necessary, the following might help. The idea is to just define a function that prints whatever it gets exactly the way you want. This does not eliminate all typing, but reduces it substantially.
---
title: "Untitled"
author: "Paul"
date: "25 September 2018"
output: html_document
---
```{r setup, include = F}
library(dplyr)
library(kableExtra)
library(knitr)
tbl_out <- function(data) {
data %>% kable("html") %>% kable_styling("hover", full_width = FALSE)
}
```
Prints as desired:
```{r test, echo = F}
head(iris) %>% tbl_out()
```
Output:
I found a work-around by using the knit_hooks() source as the formatted chunk output.
The difficulty in formatting the chunk output is that character data is passed to the hook. Drawing inspiration from the linked answer in the OP, I found a solution by evaluating the chunk source in knit_hooks().
This solution re-evaluates the chunk and is piped into the desired KableExtra formatting.
I needed to add a new chunk option table = T so that the formatting was only applied to source code that produces a data table; results = "hide" was also needed so the default chunk output was not included in the report.
---
title: "Untitled"
author: "Paul"
date: "27 September 2018"
output: html_document
---
```{r setup, include = F}
library(dplyr)
library(ggplot2)
library(kableExtra)
library(knitr)
default_source_hook <- knit_hooks$get('source')
knit_hooks$set(
source = function(x, options) {
if(is.null(options$table))
default_source_hook(x, options)
else {
eval(parse(text = x)) %>%
kable("html") %>%
kable_styling("hover", full_width = F)
}
}
)
data(iris)
```
## Normal
With no chunk options:
```{r normal}
head(iris)
```
## The desired ouptut
With chunk options `results = "hide"` and `table = T`:
```{r table_format, results = "hide", table = T, eval = F}
head(iris)
```
## It still work as normal for other other output types
With no chunk options:
```{r image}
iris %>%
ggplot(aes(x = Sepal.Length, y = Sepal.Width, group = Species)) +
geom_point()
```
There are a few problems with this solution
the code used to produce the table is now unavailable
eval = F should be included - especially if the code will take a while to run (as it is again evaluated in the hook)
I'm replacing 2 lines of code with 3 chunk options - although not a deal killer it's not quite as automagical as I would have liked.

how to use a for loop in rmarkdown?

Consider this simple example:
---
title: "Untitled"
output: ioslides_presentation
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## Slide with R Output
```{r t, warning=FALSE, message=FALSE}
library(knitr)
library(kableExtra)
library(dplyr)
for(threshold in c(20, 25)) {
cars %>%
filter(dist < threshold) %>%
kable('html') %>%
kable_styling(bootstrap_options = "striped")
}
```
Here I simply want to print each output of the for loop into a different slide. In this example, there are two calls to kablethat should go on two different slides.
The code above does not work. Am I even using the right packages for that? Any ideas?
Thanks!
You can use the asis option:
---
title: "Untitled"
output: ioslides_presentation
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(dplyr)
# needed so r will include javascript/css dependencies needed for striped tables:
kable(cars, "html") %>% kable_styling(bootstrap_options = "striped")
```
```{r, results = "asis"}
for (threshold in c(20, 25)) {
cat("\n\n##\n\n")
x <- cars %>%
filter(dist < threshold) %>%
kable('html') %>%
kable_styling(bootstrap_options = "striped")
cat(x)
}
```
To get rid of that bogus table, you can try to put options(kableExtra.html.bsTable = T) in your setup section.
Here's the start of a solution. You can print strings with markdown, either by making the strings yourself or using pander's pandoc.* functions. If you set results="asis" for that chunk, it will get compiled the same as any other markdown. I used cat to make the ## headings, but commented out two pander functions that you could try also to make headers or horizontal rules to split slides.
There's more detail on the pander functions here, plus other SO questions such as this one.
---
title: "Untitled"
output: ioslides_presentation
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(dplyr)
```
```{r, results='asis'}
for(threshold in c(20, 25)) {
# pander::pandoc.header(sprintf("Threshold = %s", threshold))
# pander::pandoc.horizontal.rule()
cat(paste("\n##", "Threshold =", threshold), "\n")
tbl <- cars %>%
filter(dist < threshold) %>%
kable(format = "html") %>%
kable_styling(bootstrap_options = "striped")
print(tbl)
}
```
One issue is that when I knit this, I'm not getting the striped table that you'd expect. If I add a slide before this chunk and put a table in it with these kableExtra settings, I do get stripes, but the first table is also pretty ugly...I'm not sure if that's a bug or conflicting CSS somewhere or what.

Resources