How to embed escape characters ("\n", "\t") into dataframe? - r

How to insert escape characters into dataframe?
It will be useful for the formatting of text data into table packages.
We could be use one universal solution for every table package (my hope).
But now we should employ a lot of approaches for the every case (depends on libraries and output formates: pdf, html).
It is really uncomfortable!
For example, we have next data
df <- data.frame("names" = c("a long long long long long ... pretty long name of the our story","Here is also long, but a little shorter"))
We see a normal output
names
1 a long long long long long ... pretty long name of the our story
2 Here is also long, but a little shorter
But how we can achieve this output ("\n")?
names
1 a long long long long long
... pretty long name of the our story
2 Here is also long, but a little shorter
I promised to add a simple example:
knit to HTML, in PDF doesn't work
```{r warning = FALSE, echo = FALSE, message=FALSE, include=FALSE,}
library(flextable)
library(gt)
#data
df <- data.frame("names" = c("a long long long \n long long ... <br> pretty long name of the our story","Here is also long, but a little shorter"))
#table one
table3 <- flextable(df)
table3 <- set_table_properties(table3, layout = "autofit", width = .5)
table3
#table two
table4 <- gt(df) %>% fmt_markdown(columns = everything())
table4
```
<center>
<caption>Table in flextable </caption>
</center>
`r table3`
<center>
<caption>Table in gt </caption>
</center>
`r table4`
In the first case - works \n, in the second - /br/ and there are only two packages!

Don't add any line breaks to your text!! This is absolutely unnecessary. All you need is the skillful use of the kableExtra package. Note the code below is the content from the RMarkdown.
The document created with it can be found here.
Add everything from ## RMarkdown Start to ## RMarkdown End to RMarkdown
Of course, don't forget to remove the comment characters before the code blocks (#```)!!
## RMarkdown Start
---
title: "LongText"
author: "Marek Fiołka"
date: "30 11 2021"
output:
html_document: default
pdf_document: default
---
#```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
#```
Prepare data frame with long text
#```{r echo=TRUE, message=FALSE, warning=FALSE}
library(stringi)
library(tidyverse)
library(kableExtra)
n=50
df = tibble(
id = 1:n,
txt = stri_rand_lipsum(n)
)
#```
See the data frame in a typical display
#```{r}
print(df)
#```
View data frame formatted with Kable Extra for HTML
#```{r}
df %>% kbl() %>%
kable_styling()
#```
View data frame formatted with Kable Extra for PDF
#```{r}
df %>% kbl() %>%
kable_paper(full_width = F) %>%
column_spec(1, bold = T, border_right = T) %>%
column_spec(2, width = "30em")
## RMarkdown End
This way you can create not only html documents but also corresponding pdf documents. Below is a fragment of a document created in this format. Note that in this case you have to use kable_paper with column_spec instead of kable_styling.
Hope this is what you were looking for.
Update
## RMarkdown Start
---
title: "LongText"
author: "Marek Fiołka"
date: "30 11 2021"
output:
pdf_document: default
html_document: default
---
#```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
#```
Prepare data frame with long text
#```{r echo=TRUE, message=FALSE, warning=FALSE}
library(stringi)
library(tidyverse)
library(kableExtra)
n=10
df = tibble(
id = 1:n,
txt = stri_rand_lipsum(n)
)
#```
See the data frame in a typical display
#```{r echo=TRUE}
print(df)
#```
View data frame formatted with [kableExtra](http://haozhu233.github.io/kableExtra/) for HTML
#```{r}
df %>% kbl() %>%
kable_styling()
#```
View data frame formatted with [kableExtra](http://haozhu233.github.io/kableExtra/) for PDF
#```{r}
df %>% kbl() %>%
kable_paper(full_width = F) %>%
column_spec(1, bold = T, border_right = T) %>%
column_spec(2, width = "30em")
#```
View data frame formatted with [gt](https://gt.rstudio.com/index.html) (only for HTML)
#```{r}
library(gt)
df %>% gt %>%
fmt_markdown(columns = everything()) %>%
tab_options(table.width = px(400))
#```
View data frame formatted with [flextable](https://davidgohel.github.io/flextable/articles/overview.html) HTML & PDF
#```{r message=FALSE, warning=FALSE}
library(flextable)
df %>% flextable %>% width(2, width = 6, unit = "in")
#```
View data frame formatted with [huxtable](https://hughjonesd.github.io/huxtable/) HTML & PDF
#```{r message=FALSE, warning=FALSE}
library(huxtable)
df %>% as_hux %>%
set_width(1) %>%
set_right_border(everywhere, 1, brdr(3, "double", "grey"))
#```
## RMarkdown End

Related

how to use gt::as_word output in a quarto file

The {{gt}} package now includes a function as_word, which outputs the table as an OOXML string.
I would like to use this to insert tables into the word output of a Quarto document.
I thought this would work.
---
title: "Untitled"
format: docx
---
```{r}
library(gt)
gtcars %>%
dplyr::select(mfr, model) %>%
dplyr::slice(1:2) %>%
gt() %>%
tab_header(
title = md("Data listing from **gtcars**"),
subtitle = md("`gtcars` is an R dataset")
) %>%
as_word()
```
But the word output is just the OOXML string, like this. How can I make the table appear as a table in the quarto word output?
No need to print an OOXML string for this purpose I guess – it works with the print() method for docx output:
```{r, echo=F}
library(gt)
gtcars %>%
dplyr::select(mfr, model) %>%
dplyr::slice(1:2) %>%
gt() %>%
tab_header(
title = "Data listing from gtcars",
subtitle = "gtcars is an R dataset"
)
```
(There's some trouble with the markdown code though, probably a bug. I've removed md().)

How to handle the overlay of kable output with page number?

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:

In RMarkdown, why is the kable table printing below the header here?

I'm trying to generate a report with each row of a tibble printing vertically in a table on its own page using a for loop. The tables are printing fine, but I want to put headers at the top of each page (and eventually, text). Since the line of code to print the header (which appears as a header in my own document but not in my reprex, not sure why) is above the line of code to print the table, using kable, I expect the header to print above the table. I suspect kable is doing something I don't understand behind the scenes but I cannot determine what.
What am I doing wrong, and how may I print headers at the top of each page?
I've provided below: a screenshot of the current output.
Relevant portion:
---
title: "kable-order-reprex"
author: "Rob Creel"
date: "6/4/2021"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(magrittr)
library(kableExtra)
```
```{r chunk1, echo=FALSE, results='asis'}
for (i in 1:nrow(mtcars)) {
# Generate Table
mtcars %>%
slice(1) %>%
stack() %>%
select(ind, values) %>%
kable(col.names = NULL) %>%
kable_styling() -> my_table
cat("\n\n\\pagebreak\n")
# Print Header
cat(paste0("## ", mtcars %>% rownames() %>% extract2(i)))
# Print Table
print(my_table)
cat("\n\n\\pagebreak\n")
}
```
Pic of mis-ordered output.:
As far as I can tell everything is working as intented. The problem is float management in LaTeX.
You can change the behaviour of the kable output by setting the argument latex_options in kable_styling(). E.g.
mtcars %>%
slice(1) %>%
stack() %>%
select(ind, values) %>%
kable(col.names = NULL) %>%
#Use either "hold_position" or "HOLD_position"
kable_styling(latex_options = "hold_position") -> my_table
hold_position corresponds to h, while HOLD_position is H, (read more about float options here), where H is stricter than h and forces the position of the float output to be at the position where it is in the code. Also see ?kable_styling (latex_options entry)
See similar question with answer here

csv file containing 2 rows and 2 columns is not rendered in R markdown

I'm trying to display a CSV file in R markdown, but it's not showing up. I use the same code for other CSV files, and it works fine. There are no errors, just an empty space.
The only difference between this CSV file and the others is that this one is exceptionally small (2 columns, 2 rows, each of the 4 cells containing a single word.)
The code that i used is this:
---
title: "Test"
author: "Me"
date: "1/8/2020"
output: html_document
---
```{r echo = FALSE, results = 'asis', include = FALSE}
library(dplyr)
library(knitr)
library(kableExtra)
```
```{r echo = FALSE, results = 'asis'}
data <- select(read.csv("test.csv", stringsAsFactors = F))
kable(data, caption = "This is data.") %>% kable_styling(bootstrap_options = "bordered", full_width = T) %>% scroll_box(width = "100%", height = "200px")
```
test.csv download
edit: here is the absolute shortest code i could make, replicating the error. this only contains essential code that is used to read and display the csv file.
```{r}
library(dplyr)
library(knitr)
library(kableExtra)
data <- select(read.csv("test.csv"))
kable(data)
```
I think the problem is the use of select:
data <- select(read.csv("test1.csv", stringsAsFactors = F))
data
> data
data frame with 0 columns and 1 row
If your remove select:
data <- read.csv("test1.csv", stringsAsFactors = F)
data
> data
column1 coumn2
1 value1 value2

how can I show my "ztable" when I use "knit to HTML" in R?

I am having a problem with my ztable,
I want to knit my Rmarkdown file to HTML but I cannot find a way to display the table I created with ztable:
z=ztable(loucaste) %>% makeHeatmap(palette = "Blues") %>% print(caption="Table 2.)
I tried to set
options(ztable.table="html")
and put this at the beginning as I read somewhere else
output: html_document
header-includes: \usepackage{colortbl}
but it doesn't work when I knit to HTML. My intention was to create a sort of formatting table similar to the ones made on excel and ztable looks like the only way.
Try this minimal Rmd. The key seems to be options(ztable.type = "html") and in the chunk that generates the table, r results='asis'
If that works for you, substitute your code in the appropriate place i.e. ztable(loucaste) %>% makeHeatmap(palette = "Blues") %>% print(caption="Table 2.).
---
title: "ztable"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ztable)
library(magrittr)
options(ztable.type = "html")
```
## R Markdown
```{r results='asis'}
matrix(1:100, nrow = 10) %>%
as.data.frame() %>%
ztable() %>%
makeHeatmap() %>%
print(caption = "table 2")
```

Resources