how to position a table in R Markdown - r-markdown

I am currently creating a document in R Markdown but I cannot position a table after a particular paragraph in the pdf. My understanding is that fig.pos="H" can be used to position the table exactly where it is in the R Markdown.
This is how I am creating my table:
```{r table_1, message=FALSE, warning=FALSE, echo=FALSE, include=FALSE, fig.pos="H", fig.cap="test", out.extra=''}
library(magrittr)
library(tidyverse)
library(kableExtra)
library(readxl)
library(modelsummary)
library(scales)
tab <- matrix(c("1", "var1", "Yes","No",
"2", "var2", "Yes","No",
"3", "var3", "Yes","Yes",
"4", "var4", "Yes","Yes",
"5", "var5", "Yes","Yes"
), ncol=4, byrow=TRUE)
colnames(tab) <- c('#','column2','column3','column4')
rownames(tab) <- NULL
tab <- as.table(tab)
table_1_output <- kbl(tab, booktabs = T, linesep = "", row.names = 0, caption = "List of variables.") %>%
kable_styling(font_size = 8)
```
```{r table_1_final, echo=FALSE, fig.pos="H", fig.cap="test", out.extra=''}
table_1_output
```
This is my R Markdown preamble:
---
title: '**title**'
author:
- name_author_1:
email: email
institute: name1
correspondence: yes
- name: name_author_2
institute: name2
- name: name_author_3
institute: name2
- name: name_author_4
institute: name3
- name: name_author_5
institute: name3
date: "14 Nov 2022"
bibliography: ref_file.bib
bib-humanities: true
output:
pdf_document:
includes:
in_header: header.tex
number_sections: yes
toc: no
pandoc_args:
- --lua-filter=scholarly-metadata.lua
- --lua-filter=author-info-blocks.lua
word_document:
toc: no
pandoc_args:
- --lua-filter=scholarly-metadata.lua
- --lua-filter=author-info-blocks.lua
html_document:
toc: no
df_print: paged
header-includes:
- |
```{=latex}
\makeatletter
\DeclareRobustCommand\and{% % \begin{tabular}
\end{tabular}%
\hskip -.5em \#plus.17fil%
\begin{tabular}[t]{c}}% % \end{tabular}
```
institute:
- name1: name1
- name2: name2
- name3: name3
---
This is my header.tex which includes:
\usepackage{amsmath}
\usepackage{pdflscape}
\usepackage{float}
\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}
\makeatletter
\patchcmd{\#maketitle}{\LARGE}{\Large}{\typeout{OK 1}}{\typeout{Failed 1}}
Do you know what I am missing?
Thank you in advance.

Related

quartopub Rmarkdown docx output

What function could help me to output data content to a Quarto-pub Docx output document?
I'm trying...
The yaml is:
---
title: "Docx Quarto output"
format:
docx:
toc: true
toc-depth: 2
number-sections: true
number-depth: 3
highlight-style: github
---
And the code:
```{r}
library(tidyverse)
text_data <- tribble(
~type, ~name, ~color,
"fruit", "apple", "red",
"vegetable", "cumcumber", "green",
"fruit", "banana", "yellow",
"grain", "rice", "white"
)
text_data %>%
split(.$type) %>%
map(~ cat('\n\n ##', .$name, '\n###', .$color))
```
What I would like to get is a Rmarkdown like:
# fruit
## apple
### red
## banana
### yellow
# vegetable
## cumcumber
### green
# grain
## rice
### white
You could try the following:
```{r}
#| results: asis
df <- text_data %>%
split(text_data$type) |>
map_dfr(~ .x |>
# little hack to avoid printing # fruit twice
mutate(string = ifelse(row_number() == 1, paste0(
"\n\n# ", type,
"\n\n## ", name,
"\n\n### ", color
),
paste0(
"\n\n## ", name,
"\n\n### ", color
)
)) |>
select(string))
cat(df$string)
```
Result:

Dynamically generating figures with captions in Word output from Rmarkdown document

I'm trying to generate a Word document with figures. I use {officedown} and {officer} packages. I need to do it dynamically, in a loop since I don't know how many figures there will be. This is my Rmarkdown code:
---
output:
officedown::rdocx_document:
plots:
caption:
style: Table Caption
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
```
```{r}
library(dplyr)
library(flextable)
library(officer)
```
```{r}
block_toc(seq_id = "fig")
```
```{r results='asis'}
ttp <- c(3, 7)
test_items <- c("item A", "item B", "item C")
fpars <- lapply(test_items, function(ti) {
fpar(
ftext("Application of "),
ftext(ti),
ftext(" Variable text - describe any test item-related effects"),
ftext(" (see "),
run_reference("fig:results1"),
ftext(")."),
fp_p = fp_par(padding.bottom = 12)
)
})
do.call(block_list, fpars)
```
```{r}
titles <- lapply(seq_len(length(ttp)), function(i) {
sprintf(
"My custom figure caption with %s, having %s side effects",
paste(test_items, collapse = ", "),
ttp[i]
)
})
```
```{r}
tmps <- lapply(seq_len(length(ttp)), function(i) {
tmp <- tempfile(fileext = ".png")
png(tmp, width = 6, height = 5, units = "in", res = 120)
plot(iris[sample(1:150, 30), i + 1:2])
dev.off()
return(tmp)
})
```
```{r}
fpars <- lapply(seq_len(length(ttp)), function(i) {
fpar(
run_autonum(
seq_id = "fig",
pre_label = "Figure ",
bkm = paste0("fig:results", i),
bkm_all = TRUE,
prop = fp_text(bold = TRUE, font.size = 12)
),
titles[[i]],
external_img(src = tmps[[i]], width = 6, height = 5)
)
})
do.call(block_list, fpars)
```
The problem is when I generate the table of figures in the rendered document. It looks like this:
An entry is kept together with the image itself, I don't know why.
I save temporary png files to be able to use them inside fpar function. Using plot function directly inside fpar causes bad effects. Maybe there's another/better way?
I found this construction useful, but unfortunately it puts captions under the figures by default. My goal is figure captions behave more like table captions, i.e. a caption is above a figure.
```{r fig.cap=unlist(titles)}
plot(iris[1:10, 1:2])
```
How can I generate the plots with captions dynamically with {officedown} or {officer} packages?
The only issue is about the last lapply, you need to put the image in a separate paragraph, so a for loop will be easier to stack 2 paragraphs into a list instead of 1 for each iteration.
---
output:
officedown::rdocx_document:
plots:
caption:
style: Table Caption
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
```
```{r}
library(dplyr)
library(flextable)
library(officer)
library(officedown)
```
```{r}
block_toc(seq_id = "fig")
```
```{r}
ttp <- c(3, 7)
test_items <- c("item A", "item B", "item C")
fpars <- lapply(test_items, function(ti) {
fpar(
ftext("Application of "),
ftext(ti),
ftext(" Variable text - describe any test item-related effects"),
ftext(" (see "),
run_reference("fig:results1"),
ftext(")."),
fp_p = fp_par(padding.bottom = 12)
)
})
do.call(block_list, fpars)
```
```{r}
titles <- lapply(seq_len(length(ttp)), function(i) {
sprintf(
"My custom figure caption with %s, having %s side effects",
paste(test_items, collapse = ", "),
ttp[i]
)
})
```
```{r}
tmps <- lapply(seq_len(length(ttp)), function(i) {
tmp <- tempfile(fileext = ".png")
png(tmp, width = 6, height = 5, units = "in", res = 120)
plot(iris[sample(1:150, 30), i + 1:2])
dev.off()
return(tmp)
})
```
```{r}
fpars <- list()
for (i in seq_along(ttp)) {
fpars[[length(fpars)+1]] <- fpar(
run_autonum(
seq_id = "fig",
pre_label = "Figure ",
bkm = paste0("fig:results", i),
bkm_all = TRUE,
prop = fp_text(bold = TRUE, font.size = 12)
),
titles[[i]]
)
fpars[[length(fpars)+1]] <- fpar(
external_img(src = tmps[[i]], width = 6, height = 5)
)
}
do.call(block_list, fpars)
```
This is an answer for "how to do it with officer" from scratch.
But the following is much more simple. There is an option fig.topcaption that do the same thing.
---
output:
officedown::rdocx_document:
plots:
caption:
style: Table Caption
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
```
```{r}
library(dplyr)
library(flextable)
library(officer)
library(officedown)
```
```{r}
block_toc(seq_id = "fig")
```
```{r fig.cap = "miaou", fig.topcaption=TRUE}
plot(cars)
```
```{r fig.cap = "ouaf", fig.topcaption=TRUE}
plot(cars)
```

How do you filter a data frame in a shiny document and display a datatable?

I'm trying to filter a data frame and then do some simple ggplots off of the data. I've tried to leverage the R studio example on Shiny documents along with the following SO post on the subject:
Reactively filtering/subsetting a data frame in shiny
Here is my code.
---
title: "Shiny Filter Test"
author: "Novice"
date: "12/13/2019"
output: html_document
runtime: shiny
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(tidyverse)
library(shiny)
inputPanel(
selectInput("n_break", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 10)
)
cdat <- reactive({
data <- tibble(x = c(10,20,35), y = c("a","b","c"))
data %>%
filter(x %in% input$n_break)
output$table <- DT::renderDT({
cdat()
}, options = list(scrollX = TRUE))
})
```
Can anyone point out where I'm going wrong? When I run the code I get my dropdown box, but that is all. No errors. Just no filtered datatable.
Thanks.
The closing brackets of your reactive are at the wrong place. They should close once you have filtered the data.
---
title: "Shiny Filter Test"
author: "Novice"
date: "12/13/2019"
output: html_document
runtime: shiny
---
```{r setup}
knitr::opts_chunk$set(
echo = FALSE
)
```
```{r}
library(tidyverse)
library(shiny)
inputPanel(
selectInput("n_break", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 10)
)
cdat <- reactive({
data <- tibble(x = c(10,20,35), y = c("a","b","c"))
data %>% filter(x %in% input$n_break)
})
DT::renderDT({
cdat()
}, options = list(scrollX = is ))
```
A remark on the reactive: if you plan to extend this futher, such that the filtered data is used elsewhere, it makes sense to do the filtering in a reactive function. However, if this is not the case I would just do the filtering inside the renderDT:
---
title: "Shiny Filter Test"
author: "Novice"
date: "12/13/2019"
output: html_document
runtime: shiny
---
```{r setup}
knitr::opts_chunk$set(
echo = FALSE
)
```
```{r}
library(tidyverse)
library(shiny)
data <- tibble(x = c(10,20,35), y = c("a","b","c"))
inputPanel(
selectInput("n_break", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 10)
)
DT::renderDT({
data %>% filter(x %in% input$n_break)
}, options = list(scrollX = TRUE))
```

R Markdown - Positioning table and plot side by side

I am using R Markdown to output to pdf, and I am trying to get a table and a plot aligned side by side horizontally. I can get fig.align = "right" to align the plot to the right of the page, but it is plotted under the table (formatted with kable) and not side by side with it. Any tips?
Here is a way using the TeX package floatrow:
---
title: "Untitled"
header-includes:
- \usepackage{floatrow}
output:
pdf_document:
keep_tex: true
---
\newfloatcommand{btabbox}{table}
\begin{figure}[H]
\begin{floatrow}
\ffigbox{%
```{r, fig.align = "right", echo = F}
plot(mpg ~ hp, data = mtcars)
```
}{\caption{A figure}}
\btabbox{%
```{r, fig.align = "right", echo = F}
knitr::kable(head(mtcars[,1:3]), format = "latex")
```
}{\caption{A table}}
\end{floatrow}
\end{figure}
I prefer the method by Martin, but if you wanted to have a less LaTeX reliant solution, you could convert the table into a grid graphic and plot it as a subfigure:
---
header-includes:
- \usepackage{subfig}
output: pdf_document
---
```{r, fig.cap='two plots', fig.subcap= c('A figure', 'A table'), out.width = '.49\\linewidth', echo = F, fig.align='center'}
library(gridExtra)
library(grid)
plot(mpg ~ hp, data = mtcars)
grid.newpage()
grid.table(head(mtcars[,1:6]), theme = ttheme_minimal())
```
I was able to do this with a combination of the multicol package and minipages. Just another option...
Here's the code:
---
title: "Untitled"
header-includes:
- \usepackage{multicol}
- \newcommand{\btwocol}{\begin{multicols}{2}}
- \newcommand{\etwocol}{\end{multicols}}
output:
pdf_document:
keep_tex: true
---
```{r minipage_funs, echo = FALSE}
## adding minipages in Rmarkdown only seems to work for me when returned from function
fig_table_mp_start <- function() {
return("\\begin{minipage}{\\textwidth}")
}
fig_table_mp_end <- function() {
return("\\end{minipage}")
}
```
`r fig_table_mp_start()`
\btwocol
```{r, fig.align = "right", echo = FALSE}
plot(mpg ~ hp, data = mtcars)
```
```{r, fig.align = "right", echo = FALSE}
knitr::kable(head(mtcars[,1:3]), format = "latex")
```
\etwocol
`r fig_table_mp_end()`
I assume you can play around with padding to make it look pretty.

Xtable grey rows overwritting vertical lines

---
title: "Title"
author: ''
date: ''
output:
pdf_document:
template: default.tex
geometry: top=0.5cm, bottom=0.5cm, left=0.5cm, right=0.5cm
header-includes: null
fontsize: 4pt
classoption: portrait
sansfont: Calibri Light
---
#Name1: `r "Name1"`
#Name2: `r "Name2"`
```{r, echo=FALSE, message=FALSE, warning=FALSE, results='asis'}
df <- mtcars
n = nrow(df)
hlines=c(-1,0,(n-1),n)
my_align = "c|c|c|ccccc|ccc|c|"
rws <- seq(1, (n-1), by = 2)
col <- rep("\\rowcolor[gray]{.90} ", length(rws))
xtable::print.xtable(xtable(df
, align = my_align)
, add.to.row = list(pos = as.list(rws), command = col)
, booktabs = F
, hline.after = hlines, type = "latex")
```
I am using an Rmarkdown to print a table which has a lot of formatting. When I add the add.to.rwo part to get grey and white alternate rows the vertical lines are removed in the grey rows.
How do I correct this? It is very difficult to create a reproducible example but hopefully the same problem will apply to any df (with the correct Latex packages behind it)
Thanks :)
Try comparing these two tables. The first is your table as you coded it, the second is done by pixiedust with the hhline option set to TRUE.
---
title: "Title"
author: ''
date: ''
output:
pdf_document:
geometry: top=0.5cm, bottom=0.5cm, left=0.5cm, right=0.5cm
header-includes:
- \usepackage{amssymb}
- \usepackage{arydshln}
- \usepackage{caption}
- \usepackage{graphicx}
- \usepackage{hhline}
- \usepackage{longtable}
- \usepackage{multirow}
- \usepackage[dvipsnames,table]{xcolor}
fontsize: 4pt
classoption: portrait
sansfont: Calibri Light
---
#Name1: `r "Name1"`
#Name2: `r "Name2"`
```{r, echo=FALSE, message=FALSE, warning=FALSE, results='asis'}
library(xtable)
df <- mtcars
n = nrow(df)
hlines=c(-1,0,(n-1),n)
my_align = "c|c|c|ccccc|ccc|c|"
rws <- seq(1, (n-1), by = 2)
col <- rep("\\rowcolor[gray]{.90} ", length(rws))
xtable::print.xtable(xtable(df
, align = my_align)
, add.to.row = list(pos = as.list(rws), command = col)
, booktabs = F
, hline.after = hlines, type = "latex")
```
```{r}
library(pixiedust)
dust(df,
hhline = TRUE,
keep_rownames = TRUE) %>%
medley_bw() %>%
sprinkle_colnames(.rownames = "") %>%
sprinkle(cols = c(".rownames", "mpg", "cyl", "qsec", "gear", "carb"),
border = "right") %>%
sprinkle(rows = nrow(mtcars),
border = "top") %>%
sprinkle(bg_pattern_by = "rows")
```