Выделение заголовков фрейма данных в rmarkdown курсивом

Я хотел бы применить форматирование в стиле латекса к заголовкам столбцов в таблице pander в rmarkdown, вяжу в pdf.

Обратите внимание, что в игрушечном документе ниже латексные команды, которые работают для элементов фрейма данных, не работают для заголовков. В частности, я хотел бы (1) иметь возможность выделять некоторые заголовки курсивом, (2) иметь возможность иметь заголовки с пробелами между буквами (на данный момент R автоматически добавляет .). Однако меня обычно интересует, как заставить заголовки в фрейме данных принимать те же латексные команды, что и элементы фрейма данных.

 ---
title: "Chapter 12: Adding to the Discrete Time Hazard Model"
output:
  pdf_document: default
  html_document: null
  word_document: null
toc: yes
linestretch: 1.3
classoption: fleqn
header-includes: 
 - \setlength{\mathindent}{0pt}
 - \setlength\parindent{0pt}
 - \usepackage{amssymb}
---

```{r global_options, include=FALSE, echo = FALSE}
#this sets global knit options (i.e. options for the entire document. The following supresses any warnings from being include in the output and sets plot parameters. Note that setting dev to pdf allows us to set size of graphs easily
rm(list = ls())

knitr::opts_chunk$set(fig.width=12, fig.height=8, fig.path='Figs/', 
                      echo=FALSE, warning=FALSE, message=FALSE, dev = 'pdf')
```

``` {r table p 446}
abC <- 0.3600344
bC <- 0.2455304 
intC <- 0.4787285


dfTrans <- data.frame("Prototype" = c("$\\textit{Left/not Blue}$", "Left/Blue", "Right/not Blue", "Right/Blue"),
                      "$LEFT$" = c(0,1,0,1),
                      "$\\textit{BLUE}$" = c(0,0,1,1),
                      `Combined Parameter Estimates` = c(paste("0 x ", round(abC,4), "+ 0 x", round(bC,4), "+ 0 x", round(intC, 4), sep = " "),  8, 9, 0))


library(pander)
panderOptions('table.split.table', 300) # this forces the table to the width of the page. 
pander(dfTrans, justify = "left")
```

person llewmills    schedule 17.02.2018    source источник


Ответы (2)


Я не уверен, как это сделать с pander, но вот метод, использующий функцию kable из knitr и kableExtra функции для подробного форматирования таблицы. Я не изменил разметку yaml, но обновленные фрагменты кода вставлены ниже, а за ними следует вывод.

```{r global_options, include=FALSE, echo = FALSE}
#this sets global knit options (i.e. options for the entire document. The following supresses any warnings from being include in the output and sets plot parameters. Note that setting dev to pdf allows us to set size of graphs easily
knitr::opts_chunk$set(fig.width=12, fig.height=8, fig.path='Figs/', 
                      echo=FALSE, warning=FALSE, message=FALSE, dev = 'pdf')

# rm(list = ls()) This is unnecessary. knitr runs the rmarkdown document in a clean session.

library(knitr)
library(kableExtra)
options(knitr.table.format = "latex")  # latex output (instead of default html)
library(tidyverse) # For dplyr pipe (%>%) and mutate
```

```{r table p 446}
abC <- 0.3600344
bC <- 0.2455304 
intC <- 0.4787285

# I've removed the latex formatting from the data frame code
dfTrans <- data.frame(Prototype = c("Italic_Left/not Blue", "Left/Blue", "Right/not Blue", "Right/Blue"),
                      LEFT = c(0,1,0,1),
                      BLUE = c(0,0,1,1),
                      `Combined Parameter Estimates` = c(paste("0 x ", round(abC,4), "+ 0 x", round(bC,4), "+ 0 x", round(intC, 4), sep = " "),  8, 9, 0))

# Remove periods in column names
names(dfTrans) = gsub("\\.", " ", names(dfTrans))
# Two other options: 
# 1. Use the data_frame function from tidyverse, rather than the base data.frame function. 
#    data_frame doesn't add periods, so you won't need to fix the column names afterwards.
# 2. Set check.names=FALSE in data.frame

# Use kableExtra cell_spec function to format on a cell-by-cell basis
dfTrans = dfTrans %>% 
  mutate(Prototype = cell_spec(Prototype, color=c("black","blue"),
                               align=rep(c("l","r"), each=2)))

# Format each of the column names using kableExtra text_spec
names(dfTrans)[1] = text_spec(names(dfTrans)[1], italic=TRUE)
names(dfTrans)[2] = text_spec(names(dfTrans)[2], align="l")
names(dfTrans)[3] = text_spec(names(dfTrans)[3], align="r", italic=TRUE, color="blue")
names(dfTrans)[4] = text_spec(names(dfTrans)[4], align="r")

# Output the table
kable(dfTrans, booktabs=TRUE, escape=FALSE) 
```

введите здесь описание изображения

Одна вещь, которую я еще не знаю, - это отформатировать только первое значение dfTrans$Prototype курсивом. cell_spec, по-видимому, использует только первое значение логического вектора italic, поэтому следующий столбец выделен курсивом:

dfTrans = dfTrans %>% 
  mutate(Prototype = cell_spec(Prototype, color=c("black","blue"),
                               align=rep(c("l","r"), each=2),
                               italic=c(TRUE, rep(FALSE, n()-1))))
person eipi10    schedule 17.02.2018

Вот решение на основе huxtable (мой пакет):

abC  <- 0.3600344
bC   <- 0.2455304 
intC <- 0.4787285
dfTrans <- data.frame(Prototype = c("Italic_Left/not Blue", "Left/Blue", "Right/not Blue", "Right/Blue"),
                  LEFT = c(0,1,0,1),
                  BLUE = c(0,0,1,1),
                  `Combined Parameter Estimates` = c(paste("0 x ", round(abC,4), "+ 0 x", round(bC,4), "+ 0 x", round(intC, 4), sep = " "),  8, 9, 0))

library(huxtable)
huxTrans <- hux(dfTrans, add_colnames = TRUE) # column names become first row
huxTrans[1, 4] <- 'Combined Parameter Estimates' # get rid of the dots
align(huxTrans)[4:5, 1] <- 'right'
text_color(huxTrans)[c(3, 5), 1] <- 'blue'
text_color(huxTrans)[1, 3] <- 'blue'
italic(huxTrans)[1, c(1, 3)] <- TRUE

huxTrans # will automatically become LaTeX in RMarkdown
quick_pdf(huxTrans)

Что выглядит в терминале так:

Терминал RStudio

И это в формате PDF:

PDF

Вы также можете добавить границы, если хотите.

person Community    schedule 17.02.2018
comment
Приятно узнать о huxtable. Я не сталкивался с этим раньше. - person eipi10; 17.02.2018