Context
I am making a table and saving it into Microsoft Word with .docx file.
the table has a variable named PM2.5. I want to subscript 2.5 like PM2.5.
In this answear, I can use the grammar 'PM~2.5~' with as_kable() to use subscrpit in PM2.5.
But when I save the result (tab), it is a blank .docx file.
Question
How can I use subscripts in gtsummary and save it into .docx file?
Reproducible code
library(dplyr)
library(gtsummary)
df = data.frame(PM2.5 = 1)
tab = # make a table using gtsummary
df %>%
tbl_summary(label = PM2.5 ~ 'PM~2.5~') %>% # subscript in main table
modify_table_styling(columns = label,
rows = label == 'PM~2.5~',
footnote = 'PM~2.5~ in footnote') %>% # subscript in footnote
as_kable()
tab %>% flextable::save_as_docx(path = 'test.docx') # a blank .docx file
The reason it is blank is because you're using flextable::save_as_docx() to save the table. That function will only work with flextables...not knitr::kable() tables.
You can put this table in an R markdown or Quarto document with output type Word, and the table will appear.
Related
I am trying to include a table in Rmarkdown that it looks like in Word. This is how I have the table in Word:
Is there a way that I can include this table exactly as the image in a Rmardown document?
Get a screenshot of the table from the document and use
![Caption for the picture.](/path/to/your/folder/imagename.png)
If we want to create a table from a model object use gtsummary or flextable
library(gtsummary)
library(flextable)
data(trial)
model <- glm(response ~ trt, trial, family = binomial)
tbl_regression(model)
as_flextable(model)
Based on the format showed, crosstable would also work
library(crosstable)
crosstable(ggplot2::mpg, class, by = drv) %>%
crosstable::as_flextable()
I want to import and modify a docx file in R with the officer package. However, when I use the suggested functions, R imports only an empty data.frame. Consider the following example:
# Packages
library("magrittr")
library("officer")
# Create example docx on computer
my_doc1 <- read_docx() %>%
body_add_par('aaa', style = 'Normal')
my_doc2 <- read_docx() %>%
body_add_par('bbb', style = 'Normal')
my_doc3 <- read_docx() %>%
body_add_par('ccc', style = 'Normal')
print(my_doc1, target = 'C:/your-path/aaa.docx')
print(my_doc2, target = 'C:/your-path/bbb.docx')
print(my_doc3, target = 'C:/your-path/ccc.docx')
# Combine all docx
my_doc_all <- read_docx() %>%
body_add_docx(src = 'C:/your-path/aaa.docx') %>%
body_add_docx(src = 'C:/your-path/bbb.docx') %>%
body_add_docx(src = 'C:/your-path/ccc.docx')
# Print combined docx to computer
print(my_doc_all, target = 'C:/your-path/all.docx')
This is my current situation. Please note that this situation is given. The previous steps can not be changed.
Now, I want to import the combined docx file and modify it in R. According to the documentation of officer (p. 26) and this thread (answer by David Gohel), I should be able to do it with the following code:
# Read combined docx file
read_my_doc_all <- read_docx("C:/your-path/all.docx")
# Return dataset representing the docx document
docx_summary(my_doc_all)
However, the output is a data.frame with one empty row:
### doc_index content_type style_name text level num_id
### 1 1 paragraph NA NA NA
I was researching on this problem myself and figured out that everything works fine, if we don't have to combine several docx documents in the forefront (as demonstrated in the beginning of this example). If we create a single file in R and export/import it, everything works fine.
How could I import a combined docx document to R with the officer package? If possible, I would like to stick to the officer package to keep the R syntax coherent.
this is a big problem for me as I need to have un-named column names inside my flextable in officer. This previously worked with the ReporteRs version.
But so far haven't been able to do this, tried using the following code:
rename(` ` = col0)
When I run try and create a flextable using this column name I get the following error message:
Error in flextable(a) :
invalid col_keys, flextable support only syntactic names
data <- head(iris) %>%
rename(` ` = Sepal.Length)
myft <- regulartable(data)
myft1<- flextable(data)
Note: the regulartable(data) works and the column name is blank.
When trying to do this with a flextable however it doesn't work and errors
Is there anyway that I am able to do this with a flextable?
Many thanks in advance
You don't need to modify your data.frame to customize the display. Having names like is risky IHMO. Read https://davidgohel.github.io/flextable/articles/layout.html#manage-headers-and-footers
library(flextable)
library(magrittr)
library(dplyr)
data <- head(iris)
myft <- regulartable(data) %>%
set_header_labels(Sepal.Length = " ")
myft1 <- flextable(data) %>%
set_header_labels(Sepal.Length = " ")
myft1
I have the following dataframe:
site_name | site_url
--------------------| ------------------------------------
3D Printing | https://3dprinting.stackexchange.com
Academia | https://academia.stackexchange.com
Amateur Radio | https://ham.stackexchange.com
I want to generate a third column with the link integrated with the text. In HTML I came up with the following pseudo code:
df$url_name <- "[content of site_name](content of site_url)"
resulting in the following working program code:
if (knitr::is_html_output()) {
df <- df %>% dplyr::mutate(url_name = paste0("[", df[[1]], "](", df[[2]], ")"))
knitr::kable(df)
}
Is there a way to this in LaTeX with knitr as well?
(I am preferring a solution compatible with kableExtra, but if this is not possible I am ready to learn whatever table package can do this.)
*** ADDED: I just noticed that the above code works within a normal .Rmd document with the yaml header output: pdf_document. But not in my bookdown project.
The problem is with knitr::kable. It doesn't recognize that the bookdown project needs Markdown output, so you need to tell it that explicitly:
df <- df %>% dplyr::mutate(url_name = paste0("[", df[[1]], "](", df[[2]], ")"))
knitr::kable(df, format = "markdown")
This will work for any kind of Markdown output: html_document, pdf_document, bookdown::pdf_book, etc.
Alternatively, if you need LaTeX output for some other part of the table, you could write the LaTeX equivalent. This won't work for HTML output, of course, but should be okay for the PDF targets:
df <- df %>% dplyr::mutate(urlName = paste0("\\href{", df[[2]], "}{", df[[1]], "}"))
knitr::kable(df, format = "latex", escape = FALSE)
For this one I had to change the column name; underscores are special in LaTeX. You could probably get away without doing that if you left it as format = "markdown", but then you'd probably be better off using the first solution.
I am trying to combine two tables in R Markdown into a single table, one below the other & retaining the header. The figure below shows the desired output. After putting my markdown code I will show the actual output. I realize that the way I have structured the pander statements will not allow me to get the output I want but searching SO I was unsuccessful in finding the right way to do so.
I can do some post processing in Word to get the output exactly as I want but I am trying to avoid that overhead.
The testdat.RData file is here: https://drive.google.com/file/d/0B0hTmthiX5dpWDd5UTdlbWhocVE/view?usp=sharing
The R Markdown RMD file is here: https://drive.google.com/file/d/0B0hTmthiX5dpSEFIcGRNQ1MzM1E/view?usp=sharing
Desired Output
```{r,echo=FALSE,message = FALSE, tidy=TRUE}
library(pander)
load("testdat.RData")
pander::pander(t1,big.mark=',', justify=c('left','right','right','right'))
pander::pander(t2,big.mark=',', justify=c('left','right','right','right'))
```
Actual Output
Thanks,
Krishnan
Here's my attempt using the xtable package:
```{r,echo=FALSE, message = FALSE, results="asis"}
library(xtable)
# Add thousands separator
t1[-1] = sapply(t1[-1], formatC, big.mark=",")
t2[-1] = sapply(t2[-1], formatC, big.mark=",")
t1$Mode = as.character(t1$Mode)
# Bind together t1, extra row of column names, and t2
t1t2 = rbind(t1, names(t1), t2)
# Render the table using xtable
print(xtable(t1t2, align="rrrrr"), # Right-align all columns (includes extra value for row names)
include.rownames=FALSE, # Don't print rownames
hline.after=NULL,
# Add midrules before/after each set column names
add.to.row = list(pos = list(-1,0,4,5),
command = rep("\\midrule \n",4)))
```
And here's the output:
Allow me to make a formal answer since my comment seemed to work for you.
pander(rbind(t1,names(t2),t2))