Creating different indent for row names in pander - r

for the purpose of exporting a results table into word using R markdown, I found that pander has fulfilled almost all my needs. However, after a lot of searching I couldn't find a way to indent some of the row names in my table (the equivalent to add_indent in kable). For example, the first row's name is: "Level 1", and than I want the second row's name ("intercept") to be indented right. Is this possible? (I found pandoc.indent but didn't succeed in applying it on my table).
Attached is the current code I use for the table.
library(pander)
set.alignment('center', row.names = 'left')
panderOptions('missing', '')
pander::pander(df,split.cell = c(50,15,15,15), split.table = Inf,
emphasize.rownames = FALSE)
Thanks!

Related

Embedding cells form one table into cells of an existing Word tables at a bookmark with flextable and officer

In Word, it is possible to copy and paste a subsection of one table into another table. For example, if I have the two Word tables below, I can copy column 2, rows 2-5 from the first table and paste them into column 2, rows 4-7 in the second table.
I can highlight the cells that I want to copy in the first table and and paste them into the cells of the second table.
I'm wondering if there is a programmatic way to do a similar operation with flextable and officer. It's probably worth mentioning the following to parameters:
Creating the second table from scratch with the values from the first table included won't work for my problem -- or at least it's a solution that I'm trying to avoid.
Adding the values from the first table to the cells of the second table one at a time with bookmarks won't work for my problem -- or at least it's a solution that I'm trying to avoid.
I've tried the following potential solutions so far. They all begin with the following template Word document with bookmarks embedded in the table.
Additionally, here is the code I'm using to create the "First table" example data.
first_table <- tibble(
n_items = 1:4,
n = c(100, 40, 20, 5)
)
Method 1: Add values to a bookmark in the second table
Start by reading in the Word template document.
doc <- read_docx("embedding_flextables_in_existing_word_tables.docx")
Then, I tried adding the values from first_table to the bookmark in the second table.
doc <- doc %>%
body_replace_text_at_bkm(
"bm_add_rows_01",
first_table %>% pull(n) %>% as.character()
)
That code results in the following error:
Error in body_replace_text_at_bkm(., "bm_add_rows_01", first_table %>% :
is_scalar_character(value) is not TRUE
So, I can't add a vector of values to the bookmark.
Method 2: Add a single-column flextable to a bookmark in the second table
To do this, I need to first coerce first_table into a single-column flextable object.
first_table_ft <- first_table %>%
select(n) %>%
flextable() %>%
delete_part("header") %>%
border_remove()
Then, add the single-column flextable to the bookmark in the second table.
doc <- doc %>%
body_replace_flextable_at_bkm("bm_add_rows_01", first_table_ft)
print(
doc,
"embedding_flextables.docx"
)
That returns the following result -- a four-row table embedded into a single cell of the second table. This result makes sense, but it isn't the result I'm attempting to achieve.
Method 3: Add a single-column flextable to a bookmark in the second table with cells merged vertically
For my third attempt, I tried adding the bookmark to the second table with rows 4-7 merged in column 2.
Then, adding the single-column flextable to the bookmark in the second table as before.
doc <- doc %>%
body_replace_flextable_at_bkm("bm_add_rows_02", first_table_ft)
print(
doc,
"embedding_flextables.docx"
)
Which again returns a result that isn't quite what I'm looking for.
Any solutions and/or constructive feedback is appreciated!

printable table with partial bolding/italics within a cell

I'm looking for a way to print out a table from R, but with formatting within a cell, like having some of the text within a cell be bold or italic. Normally I would first make the appropriate data.frame/tibble and then I'd format and print it using a package like huxtable or kable. Looking over documentation for huxtable or kableExtra, it seems as though both packages treat formatting as properties of cells, implying that within-cell formatting is either unsupported or must be implemented some other way.
If I was making a ggplot, I'd use expression for text formatting, e.g.
library(tidyverse)
ggplot(data=mtcars) +
ggtitle(expression(paste(bold("bold part"), " not bold part")))
I thought I could be clever by putting expressions into a data.frame, but this doesn't seem to be supported:
data.frame(var = c(expression(paste(bold("bold part"), "not bold part")),
expression(paste(bold("bold part"), "not bold part"))
))
#> Error in as.data.frame.default(x[[i]], optional = TRUE): cannot coerce class ""expression"" to a data.frame
If you want to make changes to data tables, I recommend you use the grid and gridExtra packages to construct your table and then make changes to the theme parameters.
Without any data to play with I can't see exactly what you want but here's a general idea of what you could do (see below). I've included other aesthetic parameters, for future reference.
You could then generate a pdf output to your C drive, which could then be printed.
d <- data.frame(A = c(1,2,3,4,5),
B = c(6,7,8,9,10),
C = c(11,12,13,14,15))
pdf("Test.pdf", height = 11, width = 10)
grid.table(d, rows = NULL, theme = ttheme_minimal(
core=list(fg_params=list(
hjust=0,
x=0.1,
fontface=matrix(c(1,2,3))))))
dev.off()
Re huxtable, you're correct, but you can get round it. Here's a 1 row, 1 column example, assuming you are printing to HTML:
my_hux <- huxtable("<b>Bold part</b> Not bold part")
escape_contents(my_hux)[1, 1] <- FALSE
You can include arbitrary HTML. Something similar would work for TeX, obviously with TeX formatting instead.

Combine tables in R Markdown

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))

multiline table header using knitr and latex [duplicate]

This question already has answers here:
Simple example of using tables + knitr for latex
(2 answers)
Closed 7 years ago.
I ended up using tables package with knitr, but I can not figure out how to get a multiline header. Here is the code:
<<test_table, results='asis', echo=FALSE>>=
matrix <- matrix(1:9, nrow = 3)
colnames(matrix) <- c("first column", "seconf column which I want to have 2 lines because of its very long header title", "third column")
library(tables)
table <- as.tabular(matrix)
latex(table)
#
It's probably possible to do this with the tables package, but xtable provides a very easy solution. The following minimal example shows two different approaches:
\documentclass{article}
\begin{document}
<<setup, echo = FALSE>>=
library(xtable)
library(knitr)
opts_chunk$set(echo = FALSE, results = "asis")
matrix <- matrix(1:9, nrow = 3)
colnames(matrix) <- c(
"first column",
"second column which I want to have 2 lines because of its very long header title",
"third column")
#
<<ChangeColumnType>>=
print(xtable(matrix, align = c("r", "r", "p{4cm}", "r")), include.rownames = FALSE)
#
<<ChangeOnlyCell>>=
colnames(matrix)[2] <- "\\multicolumn{1}{p{4cm}}{second column which I want to have 2 lines because of its very long header title}"
print(xtable(matrix), include.rownames = FALSE, sanitize.colnames.function = identity)
#
\end{document}
The first approach (chunk ChangeColumnType) is very simple: It sets the column type of column 2 to p{4cm}. That gives a column that is 4cm wide with automatic text wrapping (see wikibooks.org for more details). The drawback is, that this affects the whole column, not only the cell in the first row.
The second approach (chunk ChangeOnlyCell) uses default alignment (or whatever you want to specify via align) and changes only the column type of the problematic cell using \multcolumn.
By default, xtable "sanitizes" your table, meaning that all special latex characters will be escaped. This is handy because you cannot (easily) break your TEX code, but here we manually want to inject LaTeX code, so we have to turn this off. Therefore, set sanitize.colnames.function = identiy. All column names will be used as you specify them – so be careful when using characters with a special meaning in LaTeX.
The example from above delivers the following tables:

Strange behavior of Latex table generated by Latex() from Hmisc package and Knitr

I have some code that I am using to make a table in Knitr. I have typed in some numbers manually to make the code reproducible.
Expenditure <- as.matrix(data.frame(c("41","55","71","84"),c("41","55","71","84"),c("41","55","71","84"),c("41","55","71","84"),c("41","55","71","84"),c("41","55","71","84"),c("41","55","71","84"),c("41","55","71","84")))
rownames(Expenditure) <- c("30000","40000","50000","60000")
colnames(Expenditure) <- as.character(seq(0,0.35,0.05)*100)
latex(Expenditure,
n.cgroup=c(8), cgroup=c("Largest Historical Drawdown"),
file="",
ctable=TRUE, caption="Shortfall Risk Table", caption.loc=c('top'), label="tab:SfRisk")
This gives the following Latex code:
%latex.default(Expenditure, n.cgroup = c(8), cgroup = c("Largest Historical Drawdown"), file = "", ctable = TRUE, caption = "Shortfall Risk Table", caption.loc = c("top"), label = "tab:SfRisk")%
\ctable[caption={Shortfall Risk Table}label=tab:SfRisk,pos=!tbp,]{lllllllll}{}{\FL
\multicolumn{1}{l}{\bfseries Expenditure}&\multicolumn{8}{c}{\bfseries Largest Historical Drawdown}\NN
\cline{2-9}
\multicolumn{1}{l}{}&\multicolumn{1}{c}{0}&\multicolumn{1}{c}{5}&\multicolumn{1}{c}{10}&\multicolumn{1}{c}{15}&\multicolumn{1}{c}{20}&\multicolumn{1}{c}{25}&\multicolumn{1}{c}{30}&\multicolumn{1}{c}{35}\ML
30000&41&41&41&41&41&41&41&41\NN
40000&55&55&55&55&55&55&55&55\NN
50000&71&71&71&71&71&71&71&71\NN
60000&84&84&84&84&84&84&84&84\LL
}
This produces a Latex table, but the caption has had the word "label" added to the end, so it says "Shortfall Risk Tablelabel". The word "Tablelabel" does not appear anywhere in the .tex document. I have searched for a solution to this but I can't find anything. Any help much appreciated!
I can't post an image because I don't have a high-enough "reputation", apparently. So I have put one at johnbutters.org/examples
As per cbeleites's comment, it's a problem with the ctable code that comes out of the latex() function. The solution is to have "ctable=FALSE". This still gives the slightly odd output line: "\caption{Shortfall Risk Table\label{tab:SfRisk}}" but the final output looks OK.

Resources