I am trying to create text references for tables and figures. However, I do get it to work following the examples in the documentation. There is neither a text reference nor a table caption using either approach. Here is some example script.
# Results
See Table \#ref(tab:ResultsANOVAI) or Table \#ref(tab:ResultsANOVAII) for ANOVA results. They show that ...
(ref:ResultsANOVAI) Results ANOVA I
```{r ANOVAI, warning=FALSE, tab.cap='(ref:ResultsANOVAI)'}
library(afex)
daten <- data.frame(vp = rep(1:30, each = 6),
cond1 = rep(1:3, each = 2),
cond2 = rep(1:2),
rt = rnorm(180, 600, 100))
aov.res <- aov_ez("vp", "rt", daten, within = c("cond1", "cond2"))
apa_anova <- apa_print.afex_aov(aov.res)
apa_table(apa_anova$table)
```
A little bit of text after the table.
(ref:ResultsANOVAI) Results ANOVA II
```{r ANOVAII, warning=FALSE}
apa_anova <- apa_print.afex_aov(aov.res)
apa_table(apa_anova$table,
caption = "(ref:ResultsANOVAII)")
```
Hints are heartly welcome.
Jens
the following code should work:
# Results
See Table \#ref(tab:ANOVAI) or Table \#ref(tab:ANOVAII) for ANOVA results. They show that ...
(ref:ResultsANOVAI) Results ANOVA I
```{r ANOVAI, warning=FALSE}
library(afex)
daten <- data.frame(vp = rep(1:30, each = 6),
cond1 = rep(1:3, each = 2),
cond2 = rep(1:2),
rt = rnorm(180, 600, 100))
aov.res <- aov_ez("vp", "rt", daten, within = c("cond1", "cond2"))
apa_anova <- apa_print.afex_aov(aov.res)
apa_table(apa_anova$table, caption = "(ref:ResultsANOVAI)")
```
A little bit of text after the table.
(ref:ResultsANOVAII) Results ANOVA II
```{r ANOVAII, warning=FALSE}
apa_anova <- apa_print.afex_aov(aov.res)
apa_table(apa_anova$table,
caption = "(ref:ResultsANOVAII)")
```
So why did your code not work?
When you want to add a caption to a table via text references, add something like caption = "(ref:caption-name)" to your call to apa_table() (the chunk option tab.cap does not work)
When you are using cross references (i.e., "see Table 1 and 2"), use \#ref(tab:chunk-name) -- your chunk names are ANOVAI and ANOVAII in your example, so it has to be \#ref(tab:ANOVAI) and \#ref(tab:ANOVAII)
Hope this helps!
For further reading, the relevant parts of the papaja manual are here:
Table captions
Cross references
Related
I use kbl() function, in a rnw file that I compile in a pdf with knitr, to make a table starting from a dataframe. I use kableExtra option scale_down to adapt the table size to page size. It works fine but the table overlay with the page number of my pdf output. I'd like to know what's the best way to handle this type of problem. Thanks in advance for the help.
You could add some Latex code that puts the tabular environment into a box and resizes the content. Below is an example using \resizebox
Here's tab, a LaTex table with Gaussian random numbers generated by kable:
```{r, message = F, warning=F}
library(knitr)
library(tidyverse)
library(kableExtra)
ncol <- 10
nrow <- 30
df <- map_dfc(1:ncol, ~ data.frame(round(rnorm(nrow), 2))) %>%
set_names(letters[1:ncol])
tab <- kbl(df, format = "latex")
```
And here's how to resize it by text height/width using resizebox (see this post on tex.stackexchange for details on how the scaling works)
```{r, results='asis'}
cat(
"\\begin{table}
\\centering
\\resizebox*{\\textwidth}{\\dimexpr\\textheight-2\\baselineskip\\relax}{%",
tab,
"\n}
\\end{table}"
)
```
Result for the 30x10 table
Let's double rows and columns (ncol <- 20; nrow <- 60)
Result for 60x20 table.
I have three suggestions. The first one is maybe set your table to the next page using \newpage in your Rmarkdown code which is latex code. The second option is maybe set latex_options="HOLD_position" in your Kable_styling function. This will set the table at a certain place which maybe could help your problem. The third option is using 'longtable = TRUE` which means that the table continues on the next page. Here is the code for option one and two with:
```{r}
library(knitr)
library(tidyverse)
library(kableExtra)
df <- data.frame(x = 1:10, y = 11:20)
kable(df) %>%
kable_styling(latex_options = "HOLD_position")
```
\newpage
```{r}
kable(df) %>%
kable_styling(latex_options = "HOLD_position")
```
Which looks like this:
Here is the code for option three:
```{r}
library(tidyverse)
library(knitr)
library(kableExtra)
df <- data.frame(x = 1:50, y = 11:60)
kable(df, "latex", longtable = T, booktabs = T) %>%
kable_styling(latex_options = c("repeat_header"), font_size = 7)
```
Looks like this:
Apologies for the bad title, I wasn't sure how to best convey what my problem is.
To give some context, I want to create a personalized scorecard for each provider in our organization using Rmarkdown. I already figured out how to create an individual PDF for each provider ; however, I want to have a simple bar chart on everyone's report with the provider's position highlighted so that they can compare themselves to their peers. Below is what I have so far:
First I created the dataset:
############################## Create dataset and export #####################################
df = data.frame(
"Provider" = c("A","B","C","D"),
"Measure" = c(1.2,0.8,1.7,0.4)
)
write.csv(df, "pathway/df.csv")
Next I created an Rmarkdown file named "TEST" that calls in the dataset and includes a graph
###################### Create Rmarkdown file named "TEST" ####################################
---
output: pdf_document
---
```{r echo=FALSE}
df <- read.csv("pathway/df.csv", stringsAsFactors = FALSE)
name <- df$Provider[i]
Dear `r name`,
This is your personalized scorecard.
```{r}
ggplot() +
geom_bar(data=df, aes(x=reorder(Provider, -Measure), y=Measure,
fill = factor(ifelse(Provider == "A", "You","Your Peers"))),
stat = "identity") +
scale_fill_manual(name = "Provider", values=c("steelblue","lightgrey"))
Finally I created an R file with the for-loop to create as many PDFs as there are providers
################ Run R file with loop to make separate PDFs per Provider #####################
library(knitr)
library(rmarkdown)
#Read data
df <- read.csv("pathway/df.csv", stringsAsFactors = FALSE)
#Create loop
for (i in 1:nrow(df)){
rmarkdown::render(input = "pathway/TEST.Rmd",
output_format = "pdf_document",
output_file = paste("handout_", i, ".pdf", sep=''),
output_dir = "pathway/folder/")
}
In the code above for the ggplot2 graph I manually coded provider "A" to be highlighted in blue and the rest of the providers grey, but we have over 30 providers and I don't want to manually code for each one. If there is some way for Rmarkdown to automatically highlight each provider in blue and the rest grey for each of their PDF reports that would be amazing. Any help is much appreciated!
There were some errors in your code, so I give the correct files here.
The RMD file:
you have to submit parameters, in your case i. You also did this in name <- df$Provider[i] but i was not given. Also you have to load ggplot2 and set your chunks ob the right positions.
---
output: pdf_document
params:
i: 1
---
```{r echo=FALSE}
library(ggplot2)
df <- read.csv("df.csv", stringsAsFactors = FALSE)
name <- df$Provider[i]
```
Dear `r name`,
This is your personalized scorecard.
```{r}
ggplot() +
geom_bar(data=df, aes(x=reorder(Provider, -Measure), y=Measure,
fill = factor(ifelse(Provider == df$Provider[i], "You","Your Peers"))),
stat = "identity") +
scale_fill_manual(name = "Provider", values=c("steelblue","lightgrey"))
```
The R file loop
Here you also have to submit the parameter too.
library(knitr)
library(rmarkdown)
#Read data
df <- read.csv("pathway/df.csv", stringsAsFactors = FALSE)
#Create loop
for (i in 1:nrow(df)){
rmarkdown::render(input = "pathway/TEST.Rmd",
output_format = "pdf_document",
output_file = paste("handout_", i, ".pdf", sep=''),
output_dir = "pathway/folder/",
params = list(i = i)))}
I would like to apply some latex-style formatting to column headings in a pander table in rmarkdown, knitting to pdf.
Notice in the toy document below the latex commands that work for the elements of the dataframe do not work for the headings. Specifically I would like (1) to be able to italicise some headings, (2) to be able to have headings with spaces between the letters (at the moment R automatically adds a .). However I am generally interested in how to get the headings in a dataframe to accept the same latex commands as the elements of the dataframe.
---
title: "Chapter 12: Adding to the Discrete Time Hazard Model"
output:
pdf_document: default
html_document: null
word_document: null
toc: yes
linestretch: 1.3
classoption: fleqn
header-includes:
- \setlength{\mathindent}{0pt}
- \setlength\parindent{0pt}
- \usepackage{amssymb}
---
```{r global_options, include=FALSE, echo = FALSE}
#this sets global knit options (i.e. options for the entire document. The following supresses any warnings from being include in the output and sets plot parameters. Note that setting dev to pdf allows us to set size of graphs easily
rm(list = ls())
knitr::opts_chunk$set(fig.width=12, fig.height=8, fig.path='Figs/',
echo=FALSE, warning=FALSE, message=FALSE, dev = 'pdf')
```
``` {r table p 446}
abC <- 0.3600344
bC <- 0.2455304
intC <- 0.4787285
dfTrans <- data.frame("Prototype" = c("$\\textit{Left/not Blue}$", "Left/Blue", "Right/not Blue", "Right/Blue"),
"$LEFT$" = c(0,1,0,1),
"$\\textit{BLUE}$" = c(0,0,1,1),
`Combined Parameter Estimates` = c(paste("0 x ", round(abC,4), "+ 0 x", round(bC,4), "+ 0 x", round(intC, 4), sep = " "), 8, 9, 0))
library(pander)
panderOptions('table.split.table', 300) # this forces the table to the width of the page.
pander(dfTrans, justify = "left")
```
I'm not sure how to do this with pander, but here is a method using the kable function from knitr and kableExtra functions for detailed table formatting. I haven't changed the yaml markup, but the updated code chunks are pasted in below, followed by the output.
```{r global_options, include=FALSE, echo = FALSE}
#this sets global knit options (i.e. options for the entire document. The following supresses any warnings from being include in the output and sets plot parameters. Note that setting dev to pdf allows us to set size of graphs easily
knitr::opts_chunk$set(fig.width=12, fig.height=8, fig.path='Figs/',
echo=FALSE, warning=FALSE, message=FALSE, dev = 'pdf')
# rm(list = ls()) This is unnecessary. knitr runs the rmarkdown document in a clean session.
library(knitr)
library(kableExtra)
options(knitr.table.format = "latex") # latex output (instead of default html)
library(tidyverse) # For dplyr pipe (%>%) and mutate
```
```{r table p 446}
abC <- 0.3600344
bC <- 0.2455304
intC <- 0.4787285
# I've removed the latex formatting from the data frame code
dfTrans <- data.frame(Prototype = c("Italic_Left/not Blue", "Left/Blue", "Right/not Blue", "Right/Blue"),
LEFT = c(0,1,0,1),
BLUE = c(0,0,1,1),
`Combined Parameter Estimates` = c(paste("0 x ", round(abC,4), "+ 0 x", round(bC,4), "+ 0 x", round(intC, 4), sep = " "), 8, 9, 0))
# Remove periods in column names
names(dfTrans) = gsub("\\.", " ", names(dfTrans))
# Two other options:
# 1. Use the data_frame function from tidyverse, rather than the base data.frame function.
# data_frame doesn't add periods, so you won't need to fix the column names afterwards.
# 2. Set check.names=FALSE in data.frame
# Use kableExtra cell_spec function to format on a cell-by-cell basis
dfTrans = dfTrans %>%
mutate(Prototype = cell_spec(Prototype, color=c("black","blue"),
align=rep(c("l","r"), each=2)))
# Format each of the column names using kableExtra text_spec
names(dfTrans)[1] = text_spec(names(dfTrans)[1], italic=TRUE)
names(dfTrans)[2] = text_spec(names(dfTrans)[2], align="l")
names(dfTrans)[3] = text_spec(names(dfTrans)[3], align="r", italic=TRUE, color="blue")
names(dfTrans)[4] = text_spec(names(dfTrans)[4], align="r")
# Output the table
kable(dfTrans, booktabs=TRUE, escape=FALSE)
```
One thing I'm not sure how to do yet is to format just the first value of dfTrans$Prototype as italic. cell_spec seems to use only the first value of an italic logical vector, so the following italicizes the whole column:
dfTrans = dfTrans %>%
mutate(Prototype = cell_spec(Prototype, color=c("black","blue"),
align=rep(c("l","r"), each=2),
italic=c(TRUE, rep(FALSE, n()-1))))
Here is a huxtable-based solution (my package):
abC <- 0.3600344
bC <- 0.2455304
intC <- 0.4787285
dfTrans <- data.frame(Prototype = c("Italic_Left/not Blue", "Left/Blue", "Right/not Blue", "Right/Blue"),
LEFT = c(0,1,0,1),
BLUE = c(0,0,1,1),
`Combined Parameter Estimates` = c(paste("0 x ", round(abC,4), "+ 0 x", round(bC,4), "+ 0 x", round(intC, 4), sep = " "), 8, 9, 0))
library(huxtable)
huxTrans <- hux(dfTrans, add_colnames = TRUE) # column names become first row
huxTrans[1, 4] <- 'Combined Parameter Estimates' # get rid of the dots
align(huxTrans)[4:5, 1] <- 'right'
text_color(huxTrans)[c(3, 5), 1] <- 'blue'
text_color(huxTrans)[1, 3] <- 'blue'
italic(huxTrans)[1, c(1, 3)] <- TRUE
huxTrans # will automatically become LaTeX in RMarkdown
quick_pdf(huxTrans)
Which looks like this in the terminal:
And this in PDF output:
You can add borders as well if you want.
I'm having issues with a footnote not appearing under a table in my R Markdown report. Below is the code I'm using to process which does successfully but with no footnote appearing under the table.
```{r ccxtable7, results="asis", echo=FALSE}
comment <- list(pos = list(0), command = NULL)
comment$pos[[1]] <- c(nrow(indPctChgCC))
comment$command <- c(paste("\\hline\n",
"{\\footnotesize Note: * signifies number of
properties used was 35 or less.}\n", sep = ""))
print(xtable(valPctCon(indPctChgCC, indfreqCC, 35), align = "crrrrr",
label = "tab:indCC", add.to.row = comment, hline.after = c(-1,0),
caption = "Industrial Certified-Certified Percentage Change per Value Segment"))
```
indPctChCC is a 3x5 matrix of strings. Could someone help me understand why the footnote is not appearing under the table with this current code?
add.to.row (and also hline.after) are arguments of the print function, not xtable().
This should get you where you want:
print(xtable(tab, align = "crrr",
label = "tab:indCC",
caption = "Industrial Certified-Certified Percentage Change per Value Segment"),
add.to.row = comment,
hline.after = c(-1,0))
I am writing a small exercise book with Markdown. I would like to have the final output with the plots on a column and the document text on the other. Similar problems are addressed here and here. Unfortunately, they mainly desire one output per column. I would like to produce the output on a column and the text on the other. Really interesting is Docco, but it apprently shows the code output with the text.
A possible solution would be the RPres markdown horizontal rule: using ***, it creates two easy to use columns. But I do find documentation on its implementation in Markdown documents.
Here an image showing my results so far and an example of my code:
```{r setoption, cache=TRUE, warning=FALSE, message=FALSE, fig.width=12}
knitr::opts_chunk$set(cache=TRUE, warning=FALSE, message=FALSE, fig.width=4, echo = FALSE)
```
```{r, loadlibraries}
library(knitr)
library(lattice)
```
### Exercise 1 - 22/4/'16
Is the data set shown in the following figure symmetric or skewed? How many modes does this data set have?
```{r 1.1}
e1 <- rep(seq(1, 6, 1), c(6, 4, 2, 2, 4, 6))
barchart(table(e1), horizontal = FALSE, xlab = "", ylab = "Frequency")
```
**Solution:**
The data set is symmetric. Furthermore, it has two modes.
### Exercise 2 - 22/4/'16
Describe the shape of the dataset shown in the following figure.
```{r 2.1}
e2 <- rep(seq(1, 9, 1), c(6, 5, 4, 3, 2, 1, 1, 1, 1))
barchart(table(e2), ylab = "Frequency", horizontal = FALSE)
```
**Solution:**
The dataset is right skewed, also said right skewed, with one mode.
As you're asking for columns, my answer will be: table.
Using pipe_tables, figure and text can be alinged next to each other. However, this comes at a price:
The cells of pipe tables cannot contain block elements like paragraphs and lists, and cannot span multiple lines.
If this limitation is acceptable, pipe_tables provide a quite straightforward solution:
```{r img, fig.show = "hide", echo = FALSE}
library(knitr)
hist(rnorm(1000))
```
Figure|Explanation
-------------------------------|-------------------------
`r include_graphics(paste0(opts_chunk$get("fig.path"), "img-1.png"))`|Histogram of 1000 draws from a standard normal density.
Although the column headers cannot be omitted, you can leave them blank if desired.
Note that I initially suppress the plot (fig.show = "hide") and use include_graphics to include it afterwards. Otherwise, there would be a newline after the plot which disrupts the table.
(In knitr 1.12.3, include_graphics doesn't seem to work properly with inline code chunks. However, the current development version 1.12.25 works well.)
Extension
I hacked together an extension that allows to use a single chunk to generate and show the plots and some more features:
```{r setup, echo = FALSE}
library(knitr)
FigureNextToText <- function(number, # number of plot in chunk
text,
alt = "", # alternative text for image
label = opts_current$get("label"), # set explicitly when using inline!
ext = ".png",
headerL = " ", headerR = " ", # empty string confuses pandoc if only right header is set
widthL = 30, widthR = 30,
...) {
path <- fig_chunk(label = label, ext = ext, number = number, ...)
template <- "%s|%s
%s|%s
![%s](%s)|%s\r\n\r\n"
output <- sprintf(
template,
headerL, headerR,
paste0(rep("-", widthL), collapse = ""), paste0(rep("-", widthR), collapse = ""),
alt, path, text
)
return(asis_output(output))
}
```
```{r img, fig.show = "hide", echo = FALSE, results = "asis"}
library(knitr)
hist(rnorm(1000))
hist(runif(n = 1000, min = 0, max = 10))
FigureNextToText(1, text = "Histogram of draws from standard normal density.", widthL = 50, widthR = 10)
FigureNextToText(2, text = "Histogram of draws from uniform distribution.", headerR = "Explanation", alt = "Histogram 2.")
```
Some text.
`r FigureNextToText(2, text = "The same plot, this time inline.", label = "img", headerR = "Explanation", alt = "Histogram 2.")`
Some more text.
I know that the setup looks a little bit scary, but once FigureNextToText is defined, it can be called quite simply, e.g.:
FigureNextToText(2, text = "Histogram of draws from uniform distribution.", headerR = "Explanation", alt = "Histogram 2.")
Finding the correct values for widthL and widthR is somewhat cumbersome. This is because their effect depends on the number of characters in the cell, i.e. the filename of the image in the MD file and the alt text, too.