Placing literature references in a table in Rmd - r

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()
```

Related

Can't force page break in posterdown (RMarkdown)

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)

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.

How can I use the theme argument in the function vitae::modern_cv()

I'm updating my CV with the modern CV template of the vitae package and it's going pretty well.
According to the description I can use different themes within this template (https://pkg.mitchelloharawild.com/vitae/reference/cv_formats.html).
moderncv(..., theme = c("casual", "classic", "oldstyle", "banking", "fancy"))
However, I don't know how to incoperate this in the R Markdown header.
I have tried using brackets like vitae::moderncv(theme = "casual") but I get this error: Error: YAML output format must evaluate to a function Execution halted
I don't know how LaTeX / YAML works..
Here's an example:
---
name: Marie
surname: Curie
position: "Professor"
address: "School of Physics & Chemistry, École Normale Supérieure"
phone: +1 22 3333 4444
www: mariecurie.com
email: "Marie.Curie#ens.fr"
twitter: mariecurie
github: mariecurie
linkedin: mariecurie
date: "`r format(Sys.time(), '%B %Y')`"
output: vitae::moderncv
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)
library(vitae)
```
# Some stuff about me
* I poisoned myself doing research.
* I was the first woman to win a Nobel prize
* I was the first person and only woman to win a Nobel prize in two different sciences.
# Education
```{r}
library(tibble)
tribble(
~ Degree, ~ Year, ~ Institution, ~ Where,
"Informal studies", "1889-91", "Flying University", "Warsaw, Poland",
"Master of Physics", "1893", "Sorbonne Université", "Paris, France",
"Master of Mathematics", "1894", "Sorbonne Université", "Paris, France"
) %>%
detailed_entries(Degree, Year, Institution, Where)
```
You can set the theme in the YAML header like so:
output:
vitae::moderncv:
theme: fancy

Error: Invalid YAML front matter (ends with ':')

The loop in the params not work, and i receive this message:
Error: Invalid YAML front matter (ends with ':')
The YAML is:
---
title: "Growth"
date: "16 de julho de 2019"
output:
html_document:
toc: true
toc_depth: 5
params:
data:
default
---
I see the default thing in other post, but he not work too.
The code is below:
data <- params$data
company <- c("usim5_test.pkl", "vale_test.pkl", "csn_test.pkl", "GGBR4_test.pkl")
for (i in company) {
rmarkdown::render(
input = "C:\\Users\\Rafael\\Documents\\ibov\\gurufocus\\macro\\growth_ibov1.Rmd",
output_file = paste0("Growth_",str_sub(i, 1,5),".html"),
params = list(
data = i
)
)
}
I expect render the reports for all the files
Kinda late (three years later), but i wanted to do the something and had the same problem.
I don't know if there is now easier ways to do this since I'm not a pro on R, still, it works if you first declare data = NULL in the YAML.

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