Make the first column of an ioslides table not bold - r-markdown

I am making a presentation in RMarkdown using ioslides. I am trying to add a table of text, and the first column is bold. I would like to either make both columns bold or both columns not bold.
For example, in this presentation, the x column is bold and the y column is not:
---
title: test
output: ioslides_presentation
---
##
| x | y |
---------
| 1 | 2 |
I have also tried making the table in a chunk of R code and using kableExtra to make the second column bold, but then ioslides does not format the table nicely (and so in this case only the second column is bold, and the table does not look nice in the presentation). For example:
##
```{r, echo = FALSE}
library(kableExtra)
mat <- matrix(c(1,2), nrow = 1, dimnames = list(NULL, c('x', 'y')))
mat.kable <- kable(mat)
column_spec(mat.kable, 2, bold = TRUE)
```

You can "force" the second column to be bold. And putting a plus sign in the middle of the dashed line will give your table a proper header:
##
| x | y |
----+----
| 1 | **2** |
If using kableExtra, it is better to use kable_styling:
kable(mat) %>%
kable_styling(full_width = T, bootstrap_options = c("striped")) %>%
row_spec(0, font_size=30) # use row_spec to get control over your header. Header is row 0

Related

How to knit out table codes into table in R markdown

I am a basic-level learner of R. I am having a problem knitting out tables with a code my professor designed for the students. The code for table designs is set as below. I put this in my R markdown as below.
```{r, results="hide", message=FALSE, warning = FALSE, error = FALSE}
## my style latex summary of regression
jhp_report <- function(...){
output <- capture.output(stargazer(..., omit.stat=c("f", "ser")))
# The first three lines are the ones we want to remove...
output <- output[4:length(output)]
# cat out the results - this is essentially just what stargazer does too
cat(paste(output, collapse = "\n"), "\n")
}
```
After this, I tried printing this out with knitr.
```{r, message=FALSE, warning = FALSE, error = FALSE}
set.seed(1973)
N <- 100
x <- runif(N, 6, 20)
D <- rbinom(N, 1, .5)
t <- 1 + 0.5*x - .4*D + rnorm(N)
df.lm <- data.frame(y = y, x =x, D =D)
df.lm$D <- factor(df.lm$D, labels = c('Male', 'Female'))
##REGRESSION
reg.parallel <- lm(y ~ x + D, data = df.lm)
jhp_report(reg.parallel, title = "Result", label = "tab:D", dep.var.labels = "$y$")
```
As a result, instead of a table, it keeps on showing only the pure codes. I would like to know how I have to set up R markdown for it to print out the table instead of the codes. This is how the result looks like when I knit it.
I expected that there must be some setup options to print the table out. But I couldn't find the right one. Also, my assignment for class requires students to use this code. I did find other options like knitr::kable but I would like to use the given code for this assignment.
Thank you in advance!

How to repeatedly insert arguments from a list into a function until the list is empty?

Using R, I am working with simulating the outcome from an experiment where participants choose between two options (A or B) defined by their outcomes (x) and probabilities of winning the outcome (p). I have a function "f" that collects its arguments in a matrix with the columns "x" (outcome) and "p" (probability):
f <- function(x, p) {
t <- matrix(c(x,p), ncol=2)
colnames(t) <- c("x", "p")
t
}
I want to use this function to compile a big list of all the trials in the experiment. One way to do this is:
t1 <- list(1A=f(x=c(10), p=c(0.8)),
1B=f(x=c(5), p=c(1)))
t2 <- list(2A=f(x=c(11), p=c(0.8)),
2B=f(x=c(7), p=c(1)))
.
.
.
tn <- list(nA=f(x=c(3), p=c(0.8)),
nB=f(x=c(2), p=c(1)))
Big_list <- list(t1=t1, t2=t2, ... tn=tn)
rm(t1, t2, ... tn)
However, I have very many trials, which may change in future simulations, why repeating myself in this way is intractable. I have my trials in an excel document with the following structure:
| Option | x | p |
|---- |------| -----|
| A | 10 | 0.8 |
| B | 7 | 1 |
| A | 9 | 0.8 |
| B | 5 | 1 |
|... |...| ...|
I am trying to do some kind of loop which takes "x" and "p" from each "A" and "B" and inserts them into the function f, while skipping two rows ahead after each iteration (so that each option is only inserted once). This way, I want to get a set of lists t1 to tn while not having to hardcode everything. This is my best (but still not very good) attempt to explain it in pseudocode:
TRIALS <- read.excel(file_with_trials)
for n=1 to n=(nrows(TRIALS)-1) {
t(*PRINT 'n' HERE*) <- list(
(*PRINT 'n' HERE*)A=
f(x=c(*INSERT COLUMN 1, ROW n FROM "TRIALS"*),
p=c(*INSERT COLUMN 2, ROW n FROM "TRIALS"*)),
(*PRINT 'Z' HERE*)B=
f(x=c(*INSERT COLUMN 1, ROW n+1 FROM "TRIALS"*),
p=c(*INSERT COLUMN 2, ROW n+1 FROM "TRIALS"*)))
}
Big_list <- list(t1=t1, t2=t2, ... tn=tn)
That is, I want the code to create a numbered set of lists by drawing x and p from each pair of rows until my excel file is empty.
Any help (and feedback on how to improve this question) is greatly appreciated!

Table in Bookdown/Huskydown with several features (Citation, Caption, URL, PNG Figure, ...)

I would like to include a table in an R markdown document (Bookdown/Huskydown) which should meet the following requirements. Ideally, the table works with several output formats, e.g. LaTex/PDF and HTML.
Requirements:
Table width: fixed
Cell width: fixed
Vertical alignment: cell content aligned to the top
Text formatting: like bold or italics (best would be if md formatting supported, such that code is output agnostic) and allow for line breaks in longer texts
Citations: should be rendered
URLs: as clickable links both in HTML and LaTex/PDF
Figures: include
figures stored locally, either in
a markdown way ![](Rlogo.png) or
a knitr way knitr::include_graphics("Rlogo.png")
figures taken straight from the web
Caption for the table
Captions text formatting: caption should also allow for text formatting
Footnote: include footnotes in the table
Table numeration: tables are should be numerated
Referencing the table: in the document is needed
Notes regarding different approaches
Fixed cell width: in markdown the number of "-"s in table header determine cell width
Linebreaks:
LaTex:\\linebreak
All others: <br/>
Referencing
LaTex: add \label{foo} => \ref{foo} ( \#ref(foo))
Markdown: add Table: (\#tab:md-table) Caption==> \#ref(tab:md-table))
Comments on different approaches
Markdown: easy coding of tables in markdown
Kable & kableExtra: Versatile R markdown coding of the table, but vertical text alignment obscure and figures are not included in PDF
Pander: achieves the most, but no vertical alignment and footnotes
Huxtable: most promising, but figures are not included in PDF
This is less an answer than providing MWEs for the table shown above
```{r}
# create some random text
library(stringi)
some_text <- stri_rand_lipsum(1)
some_text <- substr(some_text, 1, 75)
# create dataframe with some stuff
figpath <- "figure/"
df <- data.frame(
Citation = c("#R-base", "#R-bookdown"),
Textfield = c("**Formatted** string<br/> -- _Everyone_ needs H^2^O", some_text),
URL = c("[R-url](https://www.r-project.org/)", "[bookdown](https://bookdown.org/)"),
fig_local_md = c(
paste0("![](", figpath, "Rlogo.png){ width=10% height=5% }"),
paste0("![](", figpath, "bookdownlogo.png){ height='36px' width='36px' }")
)#,
# not working:
# fig_local_knitr = c("knitr::include_graphics('figure/Rlogo.png')", "knitr::include_graphics('figure/bookdownlogo.png')")
)
# only include if output format is HTML, else pander throws error
if (knitr::is_html_output()) {
df$fig_web <- c("![](https://www.picgifs.com/glitter-gifs/a/arrows/picgifs-arrows-110130.gif)")
output_format <- "html"
}
if (knitr::is_latex_output()) {
output_format <- "latex"
}
```
markdown
Table: markdown table: markdown styling works in HTML (*italics*, **bold**), LaTex styling in PDF (\\textbf{bold})
| Image | Description |
| :--------------------------------------------------------- | :----------------------------------------------------------- |
| ![](figure/Rlogo.png){ width=10% height=5% } | **Image description** [#R-base] <br/>Lorem ipsum dolor sit amet, ... [R-url](https://www.r-project.org/) |
| ![](figure/bookdownlogo.png){ height='36px' width='36px' } | **Image description** [#R-bookdown] <br/>Lorem ipsum dolor sit amet, ... [bookdown](https://bookdown.org/) |
kable table
```{r kable-table, echo=FALSE, out.width='90%', fig.align = "center", results='asis'}
library(knitr)
kable(df,
caption = "kable table: markdown styling works in HTML (*italics*, **bold**), LaTex styling in PDF (\\textbf{bold})",
caption.short = "md styling works in HTML (*italics*, **bold**), LaTex styling in PDF (\\textbf{bold})"
)
```
kableExtra table
```{r kableExtra-table, echo=FALSE, out.width='90%', fig.align = "center", results='asis'}
library(kableExtra)
# http://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf
kable(
df,
caption = "kableExtra table: markdown styling works in HTML (*italics*, **bold**), LaTex styling in PDF (\\textbf{bold})",
output_format, booktabs = T, # output_format = latex, html (specify above)
# align = "l",
valign = "top"
) %>%
kable_styling(full_width = F,
latex_options = c(#"striped",
"hold_position", # stop table floating
"repeat_header") # for long tables
) %>%
column_spec(1, bold = T, border_right = T, width = "30em") %>%
column_spec(2, width = "50em") %>%
column_spec(3, width = "5em") %>%
column_spec(4, width = "10em") %>%
column_spec(5, width = "10em") %>%
footnote(general = "Here is a general comments of the table. ",
number = c("Footnote 1; ", "Footnote 2; "),
alphabet = c("Footnote A; ", "Footnote B; "),
symbol = c("Footnote Symbol 1; ", "Footnote Symbol 2"),
general_title = "General: ", number_title = "Type I: ",
alphabet_title = "Type II: ", symbol_title = "Type III: ",
footnote_as_chunk = T, title_format = c("italic", "underline")
)
```
pander table
```{r pander-table, echo=FALSE, out.width='90%', fig.align = "center", results='asis'}
library(pander)
# https://cran.r-project.org/web/packages/pander/vignettes/pandoc_table.html
pander(
df,
caption = "pander table: markdown styling works in HTML and PDF (*italics*, **bold**), LaTex styling in PDF (\\textbf{bold})",
# style = "multiline", # simple
split.table = Inf, # default = 80 characters; Inf = turn off table splitting
split.cells = c(15, 50, 5, 5, 5), # default = 30
# split.cells = c("25%", "50%", "5%", "10%", "10%"), # no difference
justify = "left"
)
```
huxtable table
```{r huxtable-table, echo=FALSE, out.width='90%', fig.align = "center", results='asis'}
library(dplyr)
library(huxtable)
# https://hughjonesd.github.io/huxtable/
hux <- as_hux(df) %>%
# huxtable::add_rownames(colname = '') %>%
huxtable::add_colnames() %>%
set_top_border(1, everywhere, 1) %>%
set_bottom_border(1, everywhere, 1) %>%
set_bottom_border(final(), everywhere, 1) %>%
set_bold(1, everywhere, TRUE) %>% # bold headlines
set_italic(-1, 1, TRUE) %>% # italics in first column (except the first row)
set_valign("top") %>%
set_width(1) %>%
set_col_width(c(0.10,0.45,0.05,0.10,0.10)) %>%
set_wrap(TRUE) %>%
set_position('left') %>% # fix table alignment (default is center)
add_footnote("Sample Footnote") %>%
set_font_size(4)
table_caption <- 'huxtable table: markdown styling works in HTML (*italics*, **bold**), LaTex styling in PDF (\\textbf{bold})'
# Print table conditional on output type
if (knitr::is_html_output()) {
caption(hux) <- paste0('(#tab:huxtable-table-explicit) ', table_caption)
print_html(hux) # output table html friendly (requires in chunk options "results='asis'")
}
if (knitr::is_latex_output()) {
caption(hux) <- paste0('(\\#tab:huxtable-table-explicit) ', table_caption)
hux # if using chunk option "results='asis'" simply output the table with "hux", i.e. do not use print_latex(hux)
}
```
Referencing the tables
works differently for different table types
Adding a short caption for the LoT
Finally adding a short caption for the table of figures is not really working as desired
(ref:huxtable-table-caption) huxtable-table caption
(ref:huxtable-table-scaption) huxtable-table short caption
```{r huxtable-table, echo=FALSE, out.width='90%', fig.align = "center", fig.cap='(ref:huxtable-table-caption)', fig.scap='(ref:huxtable-table-scaption)', results='asis'}
...
```

How can I split a table so that it appears side by side in R markdown?

I'm writing a document with R markdown and I'd like to put a table. The problem is that this table only has two columns and takes a full page, which is not very beautiful. So my question is : is there a way to split this table in two and to place the two "sub-tables" side by side with only one caption ?
I use the kable command and I tried this solution (How to split kable over multiple columns?) but I could not do the cbind() command.
Here's my code to create the table :
---
title:
author:
date: "`r format(Sys.time(), '%d %B, %Y')`"
output: pdf_document
indent: true
header-includes:
- \usepackage{indentfirst}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, echo = FALSE}
kable(aerop2, format = "markdown")
```
where aerop2 is my data frame with a list of country names in column 1 and the number of airports in each of these countries in column 2.
I have a long two-column table which is a waste of space. I would like to split this table in two sub-tables and put these sub-tables side by side with a caption that includes both of them.
This doesn't give a lot of flexibility in spacing, but here's one way to do it. I'm using the mtcars dataset as an example because I don't have aerop2.
---
output: pdf_document
indent: true
header-includes:
- \usepackage{indentfirst}
- \usepackage{booktabs}
---
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(echo = TRUE)
```
The data are in Table \ref{tab:tables}, which will float to the top of the page.
```{r echo = FALSE}
rows <- seq_len(nrow(mtcars) %/% 2)
kable(list(mtcars[rows,1:2],
matrix(numeric(), nrow=0, ncol=1),
mtcars[-rows, 1:2]),
caption = "This is the caption.",
label = "tables", format = "latex", booktabs = TRUE)
```
This gives:
Note that without that zero-row matrix, the two parts are closer together. To increase the spacing more, put extra copies of the zero-row matrix into
the list.
The solution offered by 'user2554330' was very useful.
As I needed to split in more columns and eventually more sections, I further developed the idea.
I also needed to have the tables after the text, not floating to the top. I found a way using kableExtra::kable_styling(latex_options = "hold_position").
I am writing here to share the development and to ask minor questions.
1 - Why did you add the line - \usepackage{indentfirst}?
2 - What is the effect of label = "tables" as kable() input?
(The questions are related to Latex. I probably know to little to understand the explanation in kable() documentation: "label - The table reference label"!)
---
title: "Test-split.print"
header-includes:
- \usepackage{booktabs}
output:
pdf_document: default
html_document:
df_print: paged
---
```{r setup, include=FALSE}
suppressPackageStartupMessages(library(tidyverse))
library(knitr)
library(kableExtra)
split.print <- function(x, cols = 2, sects = 1, spaces = 1, caption = "", label = ""){
if (cols < 1) stop("cols must be GT 1!")
if (sects < 1) stop("sects must be GT 1!")
rims <- nrow(x) %% sects
nris <- (rep(nrow(x) %/% sects, sects) + c(rep(1, rims), rep(0, sects-rims))) %>%
cumsum() %>%
c(0, .)
for(s in 1:sects){
xs <- x[(nris[s]+1):nris[s+1], ]
rimc <- nrow(xs) %% cols
nric <- (rep(nrow(xs) %/% cols, cols) + c(rep(1, rimc), rep(0, cols-rimc))) %>%
cumsum() %>%
c(0, .)
lst <- NULL
spc <- NULL
for(sp in 1:spaces) spc <- c(spc, list(matrix(numeric(), nrow=0, ncol=1)))
for(c in 1:cols){
lst <- c(lst, list(xs[(nric[c]+1):nric[c+1], ]))
if (cols > 1 & c < cols) lst <- c(lst, spc)
}
kable(lst,
caption = ifelse(sects == 1, caption, paste0(caption, " (", s, "/", sects, ")")),
label = "tables", format = "latex", booktabs = TRUE) %>%
kable_styling(latex_options = "hold_position") %>%
print()
}
}
```
```{r, results='asis'}
airquality %>%
select(1:3) %>%
split.print(cols = 3, sects = 2, caption = "multi page table")
```

Get a second header with the units of columns

Sometimes in academic texts one wants to present a Table in which every column has units. It is usual that the units are specified below the column names, like this
|Object |Volume | area | Price |
| |$cm^3$ |$cm^2$ | euros |
|:------------|:-------|--------:|---------:|
|A |3 | 43.36| 567.40|
|B |15 | 43.47| 1000.80|
|C |1 | 42.18| 8.81|
|D |7 | 37.92| 4.72|
How could I achieve this for my bookdown documents?
Thank you in advance.
Here is a way using kableExtra:
```{r}
library(kableExtra)
df <- data.frame(Object = LETTERS[1:5],
Volume = round(runif(5, 1, 20)),
area = rnorm(5, 40, 3),
Price = rnorm(5, 700, 200))
colNames <- names(df)
dfUnits <- c("", "$cm^3$", "$cm^2$", "€")
kable(df, col.names = dfUnits,escape = F, align = "c") %>%
add_header_above(header = colNames, line = F, align = "c")
```