Rmarkdown backticks inside inline code / inconsistent behavior with usual code chunks - r

This works in a usual code chunk in R markdown:
m1_aov <- anova(m1)
m1_aov$`Sum Sq`[2] %>% round(3)
Unfortunately, using the latter in inline code breaks the knitr parser down
`r m1_aov$`Sum Sq`[2] %>% round(3)`
Indeed, it also breaks Stackoverflow.
I looked at this related question but could not infer a working solution to my problem. Any hint?

Expanding the comment with a working example:
---
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
```{r}
a <- tibble::tibble(`a column` = 1:10) # using tibble to get a column name with a white space
m <- mean(a$`a column`)
```
Mean is `r m`
To me this looks like a neat trick because it avoids to include unecessary long code inside the text, and do not create the problem you are facing at the (small) cost of creating new objects.
The output:

Related

Long gt table pdf output breaks at the end of the page

I'm trying to generate a summary table which is quite long in a pdf format.
But the table is breaking down at the end of the page (See the image below). I guess it is something to do with page margin.
I have checked the online documentation. It has argument page.margin.bottom in tab_options() to work with a RTF format. Is there any workaround for pdf format.
The following example closely mimics my problem. But table is not breaking at the end. However, it is very close to the page margin.
library(gt)
library(tidyverse)
d = iris %>% gt()
d
gtsave(d, filename = "long_table.pdf", zoom = 0.7)
Thanks.
I have a solution using RMarkdown that converts it into a PDF. Knit (Cntrl+Shift+K) the Rmd file in RStudio to create the pdf file in your working directory.
Normally, RMarkdown uses 3 backticks (e.g. ```{r codechunk}) to create and end a code chunk. Since stackoverflow also uses 3 backticks to create a codeblock, I will swap out the Rmd codechunk 3 backticks for *** instead.
Output screenshot: https://prnt.sc/vhO5Px59mWYQ
---
title: "test_pdf"
output: pdf_document
---
***{r setup, include=FALSE}
library(tidyverse)
library(gt)
tinytex::install_tinytex() #install this if you have not already
knitr::opts_chunk$set(echo = TRUE)
***
***{r iris2, echo=F}
dfA <- iris
dfB <- iris
df <- bind_rows(dfA, dfB)
d <- df %>% gt()
d
***

How to include a dagger symbol into a kable column header

I have a table in a Rmd file to print to pdf in which I need to add a dagger symbol into a column header. The basic test code is:
---
title: "Untitled"
author: "L. G. Hunsicker"
date: "4/29/2022"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = F)
library(magrittr)
library(knitr)
library(kableExtra)
```
```{r test}
df <- data.frame(x = 1:10)
names(df)[1] <- 'maxCpep (ng/mL) †'
df %>% kbl()
```
I have tried several ways to get the dagger symbol to print, but with each effort, the outcome is that the code for the dagger symbol is simply printed as text or raises an error (with the backslash). I have tried using bquote, \dagger, \dagger, etc. I also tried to use a superscript "a" as an alternative. Again, kbl just prints the literal code text without substituting the required symbol. There must be a straight-forward way to insert special characters or math strings into a kable header, but I have been unable to find it.
Thanks in advance for any help with this issue.
Larry Hunsicker
You can directly add a Unicode escape:
df <- data.frame(x = 1:10)
names(df)[1] <- 'maxCpep (ng/mL) \u2020'
df %>% kbl()
Use intToUtf8 to get the special character.
names(df)[1] <- paste('maxCpep (ng/mL)', intToUtf8(8224))

When I knit a flextable to html there is no output with the table

The table prints nicely in markdown but is not present in the knitted html file. I noticed that it is classified as a list but don't know how to change it to an acceptable file type. The knitted output is not formatted as a table. I appreciate the help.
library("crosstable") #important package crosstable() function
library('dplyr')
library("flextable")
tbl1 = crosstable(mtcars2, c(1), by = 2) %>%
as_flextable(keep_id=FALSE)
print(tbl1)
According to ?print.flextable
Note also that a print method is used when flextable are used within R markdown documents. See knit_print.flextable().
Therefore, if we want to print in Rmarkdown, either use knitr::knit_print or remove the print as the ?knit_print.flextable documentation shows
You should not call this method directly. This function is used by the knitr package to automatically display a flextable in an "R Markdown" document from a chunk.
---
title: "Testing"
author: "akrun"
date: "09/12/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, echo = FALSE}
suppressPackageStartupMessages(library("crosstable")) #important package crosstable() function
suppressPackageStartupMessages(library('dplyr'))
suppressPackageStartupMessages(library("flextable"))
tbl1 = crosstable(mtcars2, c(1), by = 2) %>%
as_flextable(keep_id=FALSE)
# either use knit_print or remove the print wrapper
#knitr::knit_print(tbl1)
tbl1
```
-output

How to generate rmarkdown chunk within a chunk

I'm trying to generate a rmarkdown chunk using code. I've read similar questions and their solutions, such as using pander or using cat. I just can't seem to generate it. I also tried knitting the output manually. Here's an example of a Rmd file:
---
title: "test"
output: pdf_document
---
## R Markdown
```{r, results='asis',echo=FALSE}
txt <- paste("```{r}",
"2+2",
"```")
pander::pander(txt)
```
When I knit this, I get a verbatim {r} 2+2. I would like to see the number four instead. In my real example, I'm using bookdown and trying to generate a block2 chunk.
Any ideas how to generate this chunk that gets evaluated as R code?
Does this do what you want?
## R Markdown
```{r, results='asis',echo=FALSE}
txt <- paste("```{r}",
2+2,
"```")
pander::pander(txt)
```
This evalutates to
```{r} 4 ```
in your markdown document.
You using a string literal "2+2" as opposed to the expression 2+2. This is the first issue, I guess.
If you want it correctly parsed you need to add an sep = "\n" argument to paste or manually add the newline breaks.
I.e.
## R Markdown
```{r, results='asis',echo=FALSE}
txt <- paste("```{r}\n",
2+2,
"\n```", sep = "")
pander::pander(txt)
```
This evalutates to
```{r}
4
```
which is interpreted as R code in the markdown document.

Knitr output differs between Rmd and Rnw: data.table output example

Revised title to clarify focus.
We notice an anomaly that R markdown and data.table interact in a surprising way. Same does not happen when knitting LaTeX. Commands which not have a return within the R session do cause a return within the knitted markdown output. I trace the problem back to commands like the following, which do not produce an output in R,
````{r}
poolballs[ , weight2:=2 * weight]
```
but inside Rmarkdown, the output includes the full print of the poolballs DT. Same does not happen if we knit an equivalent chunk in LaTeX.
This produced some funny HTML output because I wrote chunks like this, intending to display only the first 5 lines
```{r}
poolballs[ , weight2:=2 * weight]
head(poolballs)
```
Markdown parses that as the equivalent of two chunks,
> poolballs[ , weight2:=2 * weight]
> poolballs
> head(poolballs)
Here's the markdown file to demonstrate
---
title: "Data Table Guide"
author:
- name: Paul Johnson
affiliation: Center for Research Methods and Data Analysis, University of Kansas
email: pauljohn#ku.edu
date: "`r format(Sys.time(), '%Y %B %d')`"
output:
html_document:
theme: united
highlight: haddock
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo=TRUE, comment=NA)
options(width = 70)
```
```{r make_pb_dt}
set.seed(234234)
library(data.table)
poolballs <- data.table(
number = 1:15,
weight = rnorm(15, 45.7, 0.8),
diameter = c(3, 2.9, 3.1) #shows recyling
)
poolballs
```
I want the following to show only head in line 2
```{r}
poolballs[ , weight2:=2 * weight]
head(poolballs)
```
Compare the HTML output:
http://pj.freefaculty.org/scraps/mre-dt.html
I'm sorry if this is a known feature of markdown. I've coded around this wrinkle by hiding chunks, but it seems somewhat inconvenient. Today i'm curious enough to ask you about it. I wrote the same chunks in a LaTeX file and the funny DT output problem does not happen. I put link to PDF from LaTeX in http:/pj.freefaculty.org/scraps/mre-dt-3.pdf
In your final chunk, knitr sees that you have two objects that its attempting to print and you're getting the output for both. This isn't a feature, and has been addressed in a previous question.
If you want to only print the head of the first object in that chunk, your code should be head(poolballs[, weight2:=2 * weight])

Resources