Can't force page break in posterdown (RMarkdown) - r

I am using the posterdown package in R to generate a report. My YAML and code is as follows
---
# Don't change anything from line 4 to 50 unless you know how to read it. Its the formatting
# for the report (all the colours, fonts etc)
title: <br> **Namibia Inflation Forecast Report**
author:
- name: Research & Financial Sector Development, Bank of Namibia
affiliation:
address: <br> **Updated - `r format(Sys.time(), '%B, %Y')`**
title_textsize: "85pt"
author_textsize: "60pt"
column_numbers: 3
logoright_name: Logo.png
header-includes:
- \usepackage{caption}
- \captionsetup{font=Huge}
output:
posterdown::posterdown_html:
self_contained: false
columnline_width: "3mm"
columnline_style: dashed
primary_colour: "#6d1d26"
secondary_colour: "#6d1d26"
accent_colour: "#6d1d26"
title_textcol: "#c7af76"
author_textcol: "#c7af76"
affiliation_textcol: "#c7af76"
knit: pagedown::chrome_print
---
<style>
p.caption {
font-size: 1em;
}
#main-img-left {
padding: 10px;
}
</style>
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r include=FALSE}
rm(list = ls())
source(paste0(getwd(), "/Code/LoadPackages.R")) # Check this out in the Code folder if you want to add R packages that you might need
LoadPackages()
source("Code/Tables.R", local = knitr::knit_global()) # Link to Tables code
source("Code/Charts.R", local = knitr::knit_global()) # Link to Charts Code
```
<!-- Here is where the report starts. You will notice that Each section begins with a hashtag (#), so that's how you add a title. If you want to add a subsection, you would use two hashtags. Basically, what I've done is just use the charts and tables that I've precoded in the 'Code' folder and then I pasted them into the report-->
<!-- For the Inflation Overview section, you can just change the text herein -->
# Inflation Overview
<span style="color: #6d1d26;font-weight: bold">Domestic Inflation</span> - Domestic annual headline inflation slowed to 6.9 percent in December 2022 (from 7.0 percent in November), which translates into a monthly inflation rate of 0.3 percent. The biggest contributors towards the annual rise in prices were the Transport (2.2 percentage points), Alcoholic Beverages and Tobacco (0.6 percentage points), and Housing, water, electricity, gas and other fuels (0.2 percentage points).
<span style="color: #6d1d26;font-weight: bold">Short Term Forecasts</span> - The short-term inflation forecast is presented in Table <span style="color: #6d1d26;">2</span>, with annual inflation expected to remain flat at 6.9 percent in January 2023 before declining to 6.6 percent and 6.4 percent in February and March 2023.
<span style="color: #6d1d26;font-weight: bold">Medium Term Forecasts</span> - Through the medium term, our baseline estimates suggest that inflation will average 5.2 percent and 4.3 percent in 2023 and 2024 respectively (see Figures \#ref(fig:fig1) and \#ref(fig:fig2)).
<!-- Here is the first table (Bloomberg Forecasts) -->
```{r table1, echo = FALSE, warning = FALSE, message = FALSE, results = 'asis', fig.pos='!h'}
date <- read_excel(path = 'Data/Dataset.xlsx', sheet = 'Bloomberg Forecasts') %>%
dplyr::slice(tail(row_number(), 1)) %>%
dplyr::select(`Date of Forecasts`) %>%
dplyr::mutate(`Date of Forecasts` = format(`Date of Forecasts`, format = '%d %B %Y'))
bloomberg_forecasts %>%
kable(format='html',booktabs=TRUE, align = "lccccc",
caption = "International Price Forecast Summary", escape=F) %>%
kable_styling(font_size = 45) %>%
gsub("font-size: initial !important;", "font-size: 35pt !important;", .) %>%
row_spec(0,bold=T,color = 'white', background = '#6d1d26') %>%
column_spec(1, bold=T)
```
\newpage
# Short and Medium Term Forecasts
I want this section to be on a new page
In the past, I used to be able to force a pagebreak between sections (where the section would go to the start of the next column in my report) by just using the LaTeX command \newpage. However, now when I'm trying to force the last section in my report to the next column, it's not working. Any ideas on how to fix this?
This is how it looks right now (short and medium term forecasts section doesn't want to force to a new column)
and this is how I need it to look (I always used to be able to force sections to move to the start of a new page (or column in this case)

Related

How do I dynamically adjust for text based on values of multipole columns and set as parameters in R markdown output pdf

Note the YAML. I have the title and author refer to set parameters
---
title: "`r params$ID_NUM`"
classoption: landscape
author: "`r params$first` `r params$last`"
date: "8/11/2021"
output:
pdf_document:
latex_engine: xelatex
html_document: default
params:
ID_NUM: 1
first: MICHAEL
last: DOUGLAS
---
The script below is able to output the pdf and provide me with the id number as a title. Where it does not work is it's not able to provide me the "author" portion with the corresponding name with id value. Do I do a nested for loop?
for (i in unique(df$id)) {
rmarkdown::render("Document.Rmd",
params = list(id_NUM = i),
output_file=paste0(i, ".pdf"))
}
if the dataset looks like this
id first last
1 Michael Douglas
2 Sean Penn
3 Kevin Bacon
I would like the first pdf to show
ID1
Michael Douglas
the second to show
ID2
Sean Penn
and last.
ID3
Kevin Bacon
I can get the ID portion but I can't get the names.
Update::
purrr::walk(df,function(x){
i<-df$id
p<-df$first
z<-df$last
rmarkdown::render(
"Document.Rmd",
output_file=paste0(i, ".pdf"),
params = list(id=i,first=p,last=z)
)
})
Tried with this script but did not work as well.
I believe that the following will work.
for (i in unique(df$id)) {
first <- df$first[df$id == i]
last <- df$last[df$id == i]
rmarkdown::render("Document.Rmd",
params = list(id_NUM = i, first = first, last = last),
output_file=paste0(i, ".pdf"))
}
The params values for first and last do not exist. By creating them, you should be able to get their values.

RMarkdown Won't Knit ! Package array Error: Illegal pream-token (e): `c' used

I've been trying to knit my RMarkdown file and keep getting the below error. I've tried all the debugging at https://yihui.org/tinytex/r/ and am still getting the error.
I was unable to find any missing LaTeX packages from the error log test.log.
! Package array Error: Illegal pream-token (e): `c' used.
Error: LaTeX failed to compile test.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See test.log for more info.
Here is the file I'm trying to knot
title: "test"
output:
pdf_document: default
html_document: default
---
```{r, include=FALSE}
options(tinytex.verbose = TRUE)
```
```{r echo=FALSE, message=FALSE,warning=FALSE}
library(socviz)
library(tidyverse)
library(dplyr)
library(anytime)
library(kableExtra)
library(lubridate)
library(ggplot2)
library(tidyr)
library(scales)
```
#Elementary Education PRAXIS II Scores
###2019-2020
##Overall PRAXIS II Scores
Overall PRAXIS II scores for students passing Elementary Education subtests in each completion year cohort.
Students are required to pass all four subject tests in order to be licensed in Elementary Education.
```{r echo=FALSE, message=FALSE}
library(readxl)
setwd("C:/Users/asimpfen/Desktop/Praxis")
PRAXIS_201819_UVM_Var_NetID <- read_excel("C:/Users/asimpfen/Desktop/Praxis/PRAXIS 201819-UVM Var. NetID.xlsx")
PRAXIS_201920_UVM_Var_NetID <- read_excel("C:/Users/asimpfen/Desktop/Praxis/PRAXIS 201920-UVM Var. NetID.xlsx")
Sub_test_codes <- read_excel("C:/Users/asimpfen/Desktop/Praxis/Sub test codes.xlsx")
#merge praxis scores together
PRAXIS_All<-rbind(PRAXIS_201819_UVM_Var_NetID,PRAXIS_201920_UVM_Var_NetID)
#select ELED students only
ELED<-filter(PRAXIS_All,UG_Degree_Major=="ELK6",Pass___Not_Pass == "Passed")
#remove PRAXIS Core scores
ELED<-ELED[(ELED$Test_Name =='5002 Elem Ed: MS Reading & Language Arts Subtest'|ELED$Test_Name =='5003 Elem Ed: MS Mathematics Subtest'|ELED$Test_Name=='5004 Elem Ed: MS Social Studies Subtest'|
ELED$Test_Name =='5005 Elem Ed: MS Science Subtest'),]
#change test date to correct format
ELED$Test_Date<-anytime(ELED$Test_Date)
#create UVM licensure requirement variable
ELED<-ELED%>%mutate(UVM_Lic_Rec=case_when(
(.$UG_Degree_Term==201801 & .$Test_Date<=as.POSIXct('2019-05-30')~"2018"),
(.$UG_Degree_Term==201806 & .$Test_Date<=as.POSIXct('2019-08-31')~"2019"),
(.$UG_Degree_Term==201809 & .$Test_Date<=as.POSIXct('2019-12-31')~"2019"),#this worked
(.$UG_Degree_Term==201901 & .$Test_Date<=as.POSIXct('2020-05-30')~"2019"),
(.$UG_Degree_Term==201906 & .$Test_Date<=as.POSIXct('2020-08-31')~"2019"),
(.$UG_Degree_Term==201909 & .$Test_Date<=as.POSIXct('2020-12-31')~"2020"),
(.$UG_Degree_Term==202001 & .$Test_Date<=as.POSIXct('2021-05-30')~"2020"),
(.$UG_Degree_Term==202006 & .$Test_Date<=as.POSIXct('2021-08-31')~"2020"),TRUE~'No Lic'))
#fix specific instances where students were granted exemption to one year rule
ELED$UVM_Lic_Rec[ELED$netid=='lhandy' & ELED$Test_Name=='5005 Elem Ed: MS Science Subtest']<-'2020'
ELED$UVM_Lic_Rec[ELED$netid=='lhandy' & ELED$Test_Name=='5004 Elem Ed: MS Social Studies Subtest']<-'2020'
#create CAEP completer variable year
ELED$CAEP_Comp_Yr<-with(ELED,
ifelse(UVM_Lic_Rec==2018 & Test_Date<=as.POSIXct("2018-08-31"),'2018',
ifelse(UVM_Lic_Rec==2018 & Test_Date<=as.POSIXct("2019-08-31"),'2019',
ifelse(UVM_Lic_Rec==2019 & Test_Date<=as.POSIXct("2019-08-31"),'2019',
ifelse(UVM_Lic_Rec==2019 & Test_Date<=as.POSIXct("2020-08-31"),'2020',
ifelse(UVM_Lic_Rec==2020 & Test_Date<=as.POSIXct("2020-08-31"),'2020',
ifelse(UVM_Lic_Rec==2020 & Test_Date<=as.POSIXct("2021-08-31"),'2021',NA)))))))
ELED1<-select(ELED,netid,UG_Degree_Year,UG_Degree_Term,Test_Date,Test_Name,Score,CAEP_Comp_Yr,UVM_Lic_Rec)
#pivot data so that there the individual ELED tests are each a column for CAEP Completion
test1<-pivot_wider(ELED1,id_cols = netid ,names_from = c(Test_Name,CAEP_Comp_Yr),values_from = Score, values_fn = max)
CAEP<-pivot_wider(ELED,id_cols = netid ,names_from = Test_Name,values_from = CAEP_Comp_Yr, values_fn = max)
#drop students who have not passed all four exams
CAEP<-CAEP[complete.cases(CAEP[,2:5]),]
#select max value for final CAEP completion year
CAEP$CAEP_Comp_Final<-pmax(CAEP$`5002 Elem Ed: MS Reading & Language Arts Subtest`,CAEP$`5003 Elem Ed: MS Mathematics Subtest`,CAEP$`5004 Elem Ed: MS Social Studies Subtest`,CAEP$`5005 Elem Ed: MS Science Subtest`)
#merge back into main CAEP data set
ELED<-merge(x=ELED,CAEP[,c("netid","CAEP_Comp_Final")],by="netid",all.x = TRUE)
#pivot data so that there the individual ELED tests are each a column for ROPA/Title II Completion
test1<-pivot_wider(ELED1,id_cols = netid ,names_from = c(Test_Name,CAEP_Comp_Yr),values_from = Score, values_fn = max)
ROPA<-pivot_wider(ELED,id_cols = netid ,names_from = Test_Name,values_from = UVM_Lic_Rec, values_fn = max)
#drop students who have not passed all four exams
ROPA<-ROPA[complete.cases(ROPA[,2:5]),]
#remove those who did not receive their license
test3<-ROPA%>%
filter_all(all_vars(!grepl('No Lic',.)))
#select max value for final CAEP completion year
ROPA$ROPA_Comp_Final<-pmax(ROPA$`5002 Elem Ed: MS Reading & Language Arts Subtest`,ROPA$`5003 Elem Ed: MS Mathematics Subtest`,ROPA$`5004 Elem Ed: MS Social Studies Subtest`,ROPA$`5005 Elem Ed: MS Science Subtest`)
#merge back into main CAEP data set
ELED<-merge(x=ELED,ROPA[,c("netid","ROPA_Comp_Final")],by="netid",all.x = TRUE)
#remove ELED students who have not completed or are outside the desired range
ELED<-ELED[!is.na(ELED$CAEP_Comp_Final),]
#change Score to numeric value
ELED$Score<-as.numeric(ELED$Score)
#create tables
ELED_Sum<-ELED%>%
group_by(Test_Name,CAEP_Comp_Final)%>%
summarize(N=n())
ELED_Score<-ELED%>%
group_by(Test_Name,CAEP_Comp_Final)%>%
summarize(N=n(),Avg=mean(Score,round(2)))
ELED_Score1<-pivot_wider(ELED_Score,id_cols = CAEP_Comp_Final ,names_from = Test_Name,values_from = Avg)
#Rename completion year
colnames(ELED_Score1)[colnames(ELED_Score1)=='CAEP_Comp_Final']<-'Completion Year'
kbl(ELED_Score1)%>%
kable_classic()%>%
row_spec(0,bold = TRUE,align = 'center')%>%
row_spec(1:2,align = 'center')%>%
add_header_above(c("","Overall Subject Test Scores"=4))
```

Placing literature references in a table in Rmd

I am trying to produce a table within my Rmd that includes references. This sits within a manuscript that will contain these and other references. Within the manuscript I'm able to use [#xxxx] ok. I tried this as a column in the table and using the gt, Datatable and Flextable packages with no success.
This is what my Rmd looks like
---
title: "test"
author: "David"
date: "27/01/2021"
output: html_document
bibliography: test.bib
---
test[#guan_clinical_2020]
``` {r, echo = F}
library("gt")
gt(dplyr::tibble("study_id" = c(1,2),
"lead_author" = c("Guan, Ni", "Guan, Liang"),
"sample_size" = c(1099, 1590),
"refs" = c("[#guan_clinical_2020]",
"[#guan_comorbidity_2020]")))
```
# **References**
The test.bib file looks like this.
#article{guan_clinical_2020,
title = {Clinical {Characteristics} of {Coronavirus} {Disease} 2019 in {China}},
copyright = {Copyright © 2020 Massachusetts Medical Society. All rights reserved.},
url = {https://www.nejm.org/doi/10.1056/NEJMoa2002032},
doi = {10.1056/NEJMoa2002032},
abstract = {Original Article from The New England Journal of Medicine — Clinical Characteristics of Coronavirus Disease 2019 in China},
language = {en},
urldate = {2020-07-21},
journal = {New England Journal of Medicine},
author = {Guan, Wei-jie and Ni, Zheng-yi and Hu, Yu and Liang, Wen-hua and Ou, Chun-quan and He, Jian-xing and Liu, Lei and Shan, Hong and Lei, Chun-liang and Hui, David S. C. and Du, Bin and Li, Lan-juan and Zeng, Guang and Yuen, Kwok-Yung and Chen, Ru-chong and Tang, Chun-li and Wang, Tao and Chen, Ping-yan and Xiang, Jie and Li, Shi-yue and Wang, Jin-lin and Liang, Zi-jing and Peng, Yi-xiang and Wei, Li and Liu, Yong and Hu, Ya-hua and Peng, Peng and Wang, Jian-ming and Liu, Ji-yang and Chen, Zhong and Li, Gang and Zheng, Zhi-jian and Qiu, Shao-qin and Luo, Jie and Ye, Chang-jiang and Zhu, Shao-yong and Zhong, Nan-shan}
}
#article{guan_comorbidity_2020,
title = {Comorbidity and its impact on 1590 patients with {COVID}-19 in {China}: a nationwide analysis},
volume = {55},
copyright = {Copyright ©ERS 2020. http://creativecommons.org/licenses/by-nc/4.0/This version is distributed under the terms of the Creative Commons Attribution Non-Commercial Licence 4.0.},
issn = {0903-1936, 1399-3003},
shorttitle = {Comorbidity and its impact on 1590 patients with {COVID}-19 in {China}},
url = {https://erj.ersjournals.com/content/55/5/2000547},
doi = {10.1183/13993003.00547-2020}
}
The reference after test works fine, unfortunately I cant get the ones within the table to work.
ftExtra may be solution here:
---
title: "test"
author: "David"
date: "27/01/2021"
output: html_document
bibliography: test.bib
---
test[#guan_clinical_2020]
``` {r, echo = F}
library("flextable")
library("ftExtra")
dat <- dplyr::tibble("study_id" = c(1,2),
"lead_author" = c("Guan, Ni", "Guan, Liang"),
"sample_size" = c(1099, 1590),
"refs" = c("[#guan_clinical_2020]",
"[#guan_comorbidity_2020]"))
dat %>%
flextable() %>%
colformat_md() %>%
autofit()
```

How do I get a shorter Runtime?

num<-18.7
guess<- -1
print("Can you guess the daily dose per 1000 inhabititants in the UK?")
while(guess !=num) {
guess<-readline(prompt = "Enter integer:")
if (guess== num)
cat(num, "is correct")
if (guess<num)
cat("it is bigger")
if (guess>num)
cat("It is smaller")
}
It works when I play it through r script but when I knit it into markdown it doesn't get an error or anything but its been running for about 30 minutes and still hasn't finished. Is there a way to change this?
As mentioned in the comments, the R code in a R Markdown document is executed when it is knitted, not when it is viewed. When talking about interactivity for R, one usually thinks about Shiny. For some cases it is also possible to combine Shiny directly with R Markdown, c.f. https://bookdown.org/yihui/rmarkdown/shiny-documents.html. A straight forward conversion of your script gives:
---
runtime: shiny
output: html_document
---
# Can you guess the daily dose per 1000 inhabititants in the UK?
```{r setup, include=FALSE}
num <- 18.7
```
```{r guessing-game, echo=FALSE}
numericInput("guess", label = "Enter number:", value = 0)
renderText({
if (input$guess == num)
paste(num, "is correct")
else if (input$guess<num)
"it is bigger"
else if (input$guess>num)
"It is smaller"
})
```
Such a document can either be run locally or deployed. BTW, == is not the best choice for comparing floating point numbers. It is better to use isTRUE(all.equal()):
> 0.3 == 0.1 + 0.1 + 0.1
[1] FALSE
> isTRUE(all.equal(0.3, 0.1 + 0.1 + 0.1))
[1] TRUE

How to format Gmisc::htmlTable

Below is an rmarkdown document that can be pasted into rstudio.
My problem is that output from htmlTable is prepended/appended with cruft from the htmlTable attributes.
---
title: "SO_question"
author: "AC"
date: "Wednesday, May 28, 2014"
output:
html_document:
theme: readable
---
My heading
============
This is a few tables. Notice that `htmlTable` prints `[1]"` before each table and `" attr(,“class”) [1] “htmlTable” “character” [1] “` after each table. How can I avoid this?
``` {r html_table, results='asis', echo=FALSE, message=FALSE}
library("htmlTable")
library("reshape2")
#Chick weight example
names(ChickWeight) <- tolower(names(ChickWeight))
chick_m <- melt(ChickWeight, id=2:4, na.rm=TRUE)
for (i in unique(chick_m$diet)) {
diet <- subset(chick_m, diet==i)
table_to_print <- dcast(chick_m, time ~ variable, mean)
print(htmlTable(table_to_print, rgroup=c(""), n.rgroup=nrow(table_to_print)))
}
```
Bonus question: How to format the last row in each table as bold text (suited for a 'total' row)?
Rather than using print on your htmTable, use cat to properly render it.
for (i in unique(chick_m$diet)) {
diet <- subset(chick_m, diet==i)
table_to_print <- dcast(chick_m, time ~ variable, mean)
cat(htmlTable(table_to_print, rgroup=c(""), n.rgroup=nrow(table_to_print)))
}
There is a print.htmlTable function that is called when a print is performed on an object from the htmlTable function. It should automatically call the cat, not sure if this was true May '14 but it works today.
In the 1.1 version of the htmlTable-package (the function was separated from the Gmisc-package) there is a total option:
for (i in unique(chick_m$diet)) {
diet <- subset(chick_m, diet==i)
table_to_print <- dcast(chick_m, time ~ variable, mean)
print(htmlTable(table_to_print, total=TRUE))
}
Note: You do not need to specify the rgroup element if you are not using it.
#author

Resources