I'm trying to save a kableExtra table to a png that contains an equation.
A really simple example:
tab <- kable("$a^2$")
tab
which gives me the table I'm looking for:
Now I want to save this to a png or jpg file with save_kable
save_kable(tab, file = "test.jpg")
which then returns this:
I have already tried changing the escape argument but the result remains the same
tab <- kable("$a^2$", escape = TRUE)
tab <- kable("$a^2$", escape = FALSE)
Any ideas how to make sure the png or jpg file also renders the equation/mathsymbols?
Thanks!
I propose one solution based on two other packages:
library(knitr)
library(gridExtra) # to display a table
library(latex2exp) # for TeX function which transform $$ to expression
png("test.png")
grid.table(TeX(kable("$a^2$", format = "simple")))
dev.off()
escape will work only for colnames in kable().
Related
I am working in rmarkdown to produce a report that extracts and displays images extracted from word and powerpoint.
To do this, I am using the officer package. It has a function called media_extract which can 'extract files from an rdocx or rpptx object'.
I have two issues:
How to view or use the image after I have located it.
In word, how to locate the image without the media_path column.
I have been able to locate an image in pptx using this function: the pptx_summary function creates a data frame with a media_path column, which displays a file path for image elements. The media_path is then used as an argument in the media_extract function to locate the image. See example code from package documentation below:
example_pptx <- system.file(package = "officer",
"doc_examples/example.pptx")
doc <- read_pptx(example_pptx)
content <- pptx_summary(doc)
image_row <- content[content$content_type %in% "image", ]
media_file <- image_row$media_file
png_file <- tempfile(fileext = ".png")
media_extract(doc, path = media_file, target = png_file)
However, when I run media_extract it returns 'TRUE', which is the example output, but I am unsure how to add the image to my report. I've tried assigning the media_extract as a value eg
image <- media_extract(doc, path = media_file, target = png_file)
but this returns 'FALSE'.
How do I include the image as an image in my report?
The second issue I'm having is how to locate an image in word. The documentation for media_extract says it can be used to extract images from both .docx and .pptx, I have only managed to get it to work for the latter. I haven't been able to create a file path for .docx.
The file path is generated using either; docx_summary or pptx_summary, depending on the file type, which create a data frame summary of the files. The pptx_summary includes a column media_path, which displays a file path for the image. The docx_summary data frame doesn't include this column. Another stackoverflow post posed a solution for this using word/media/ subdir which seemed to work, however I'm not sure what this means or how to use it?
How do I extract an image from a word doc, using word/media/ subdir as the media path?
media_extract() is a function that copy the media where you want. We can show the extracted images using R Markdown with at least 3 methods:
knitr::include_graphics()
regular markdown
magick::image_read()
They are illustrated below:
---
title: "media_extract usage"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(officer)
library(flextable)
example_pptx <- system.file(package = "officer",
"doc_examples/example.pptx")
doc <- read_pptx(example_pptx)
content <- pptx_summary(doc)
image_row <- content[content$content_type %in% "image", ]
media_file <- image_row$media_file
png_file <- tempfile(fileext = ".png")
media_extract(doc, path = media_file, target = png_file)
```
## include_graphics
```{r out.width="200px"}
knitr::include_graphics(png_file)
```
## markdown
You can't use `tempfile()` here - path is better when defined as relative.
Let's write it to "./file.png".
```{r results='hide'}
media_extract(doc, path = media_file, target = "file.png")
```
![](file.png){style="width:200px;"}
## magick
```{r out.width="200px"}
magick::image_read(png_file)
```
I have continued to research the second issue and found an answer, so thought I would share!
The difficultly I was having extracting images from docx was due to the absence of a media_file column in the summary data frame (produced using docx_summary), which is used to locate the desired image. This column is present in the data frame produced for pptx pptx_summary and is used in the example code from the package documentation.
In the absence of this column you instead need to locate the image using the document subdirectory (file path when the docx is in XML format), which looks like: media_path <- "/word/media/image3.png"
If you want see what this structure looks like you can right click on your document >7-Zip>Extract files.. and a folder containing the document contents will be created, otherwise just change the image number to select the desired image.
Note: sometimes images have names that do not follow the image.png format so you may need to extract the files to find the name of the desired image.
Example using media_extract with docx.
#extracting image from word doc using officer package
report <- read_docx("/Users/user.name/Documents/mydoc.docx")
png_file <- tempfile(fileext = ".png")
media_file <- "/word/media/image3.png"
media_extract(report, path = media_file, target = png_file)
Package "table1" allows for some amazing tables to be made. However, i can't figure how to export one to .doc format.
Here is an example code:
table1( ~ x | Y, data = df)
I wonder if it is possible to somehow save resulting table into .doc format so it still looks like this:
Turns out it's very simple:
Just cmd+a the table in Rstudio viewer -> cmd+c -> paste Special in MS Word -> chose .html format!
I'm sorry to dig this up. However I learnt to love the two packages table1 and aswell flextable and one other route would be to fastly convert the table1 object to a flextable
library(table1)
library(flextable)
library(magrittr)
# Create Table1 Object
tbl1<- table1(~Sepal.Length+Sepal.Width|Species,data=iris)
# Convert to flextable
t1flex(tbl1) %>%
save_as_docx(path="Iris_table1.docx")
Note that this give you the full flexibility over working with a flextable and an easy and save way to export to word. A nice guide on additional formatting with flextable can be found here
Another possible solution:
The above strategy did not work for me when I had a similar issue, but it was resolved once I knitted the table1 object and opened the html in browser to copy the html table and successfully paste into word. Doing it within RStudio viewer would not work for me for some reason.
You can also save it as a .csv file for further manipulation (and from there to word)
mytable <- table1( ~ x | Y, data = df)
write.table (mytable , "my_table_1_file.csv", col.names = T, row.names=F, append= T, sep=',')
I have 3 R plots saved as pdf files (upper_left.pdf, upper_right.pdf, lower.pdf) as vector graphic and want to make a one-page pdf file and arrange them on it as follows:
What I have tried already
I have tried reading the pdf's using magick::image_read_pdf and appending them using magick::image_append. More specifically,
library(magick)
panel.ul <- image_read_pdf("upper_left.pdf")
panel.ur <- image_read_pdf("upper_right.pdf")
panel.l <- image_read_pdf("lower.pdf")
whole <- c(panel.ul, panel.ur) %>%
image_append() %>%
c(panel.l) %>%
image_append(stack = TRUE)
The first issue is magick::image_read_pdf imports the plot as png (if I'm right, not vector graphic though).
magick::image_append also 'works' and gives me what I want in viewer pane (in RStudio, next to Help).
I then try to save them using export::graph2pdf(whole), but it gives me a blank page.
So, if I am to use magick, there are two issues that need to be solved:
importing plots as vector graphic objects (do not know the technical term in R)
Exporting the stacked plot to a vector pdf file.
How can I solve it? thanks in advance.
You're basically done. You only need to add
plot(whole) # plot the external object generated in ImageMagick to R's plotting device
savePlot(type = "pdf") # saves the current plotting device to a pdf file.
You will find your plot in your workoing directory called "Rplot.pdf".
savePlot has many options to customize your pdf output. Make sure to check ?savePlot.
To recreate your scheme from above youll need to temporarily save the upper panel as a separate pdf before you paste it to on top of the lower panel:
whole2 <- image_append(c(panel.ul, panel.ur))
plot(whole2)
savePlot("whole2.pdf", type = "pdf")
If the upper and lower panel do not look proportionate you can use the heght and width parameters of savePlot to adjust the size of the first pdf.
panel.upr <- image_read_pdf("whole2.pdf")
final <- image_append(c(image_append(panel.upr),panel.l), stack = TRUE)
plot(final)
savePlot("final.pdf", type = "pdf")
How do I go about removing the output shown in the picture below after I use read_excel to import the data in r markdown. Basically I don't want there to be any output after this function. Please see attached image.
bdims <- read_excel("bdims.xlsx")
head(bdims)
You can set results = 'hide'. So if eg. for standard rmarkdown. This will stop the output from showing. Read on the cheat sheet how to use other settings such as echo and eval
{results = 'hide'}
bdims <- read_excel("bdims.xlsx")
or with roxygen document for rendering rmarkdown,
#+ results = 'hide'
bdims <- read_excel("bdims.xlsx")
I am trying to include links to particular webpages in a 'kable' table in Rmarkdown, when creating a pdf.
The table has 4 columns, and I wish for the links to be in the second column, which currently includes strings. The output of the table is given below;
knitr::kable(ind_rank_table_final,row.names = FALSE,caption = "Industry Rank",align = rep("l",ncol(ind_rank_table)))
Using paste0, you can construct markdown-formatted URLs in your dataframe, and then pass that to kable, like so:
---
output: pdf_document
---
```{r}
# some urls
urls <- rep("https://stackoverflow.com/", 10)
# use paste0 to compose markdown-formatted hyperlinks
mtcars$mpg <- paste0("[", mtcars$mpg, "](", urls, ")")
# print the table, with hyperlinked text
knitr::kable(head(mtcars))
```
And you can see the result, blue text in the mpg column, and if I hover my mouse over, I see the URL:
If you want to print the URLs in the table, and have them clickable, then you'de do something like this mtcars$mpg <- paste0("[", urls, "](", urls, ")") like so:
Is that what you're after? This use of paste0 is pretty handy for doing all sorts of things to tables, for example, combining multiple values in one cell, and applying conditional formatting (like bold for significant values)
For those knitting to PDFs using bookdown, #Ben's answer will not get you fully the way there. As #mavericks pointed out, you will still see the full text ([21](https://stackoverflow.com/), to keep with #maverick's example).
To fix this, add the argument format = "pipe" or format = "simple" to kable(). The "latex" option, while generating a working link, will display like #maverick's example. The default behavior for kable() is to automatically determine the format, which I guess in the case of a bookdown document must be "latex"?
I don't know, but this should generate #Ben's first table for bookdown users:
output: bookdown::pdf_document2
# some urls
urls <- rep("https://stackoverflow.com/", 10)
# use paste0 to compose markdown-formatted hyperlinks
mtcars$mpg <- paste0("[", mtcars$mpg, "](", urls, ")")
# print the table, with hyperlinked text
knitr::kable(head(mtcars), format = "simple")