如何在后续页面上重复列标题并使用xtable对行进行颜色交替?

时间:2017-03-01 19:09:08

标签: knitr r-markdown xtable

我可以使用longtable让列标题在后续页面上重复,并且我能够替换行颜色,但我无法弄清楚如何使用add.to来组合这两个。行。下面是显示两个表的示例Markdown代码。

---
title: "Test"
header-includes:
   - \usepackage{fontspec}
   - \setmainfont{Arial}
   - \usepackage{fancyhdr}
   - \usepackage{booktabs} # For Colored rows in tables
   - \usepackage[table]{xcolor} # For Colored rows in tables
   - \usepackage{longtable}
output:
  pdf_document:
    latex_engine: xelatex
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Table with repeating headers

```{r table1, results='asis'}
library(knitr)
library (xtable)

x <- iris

add.to.row <- list(pos = list(0), command = NULL)
command <- paste0("\\hline\n\\endhead\n",
                  "\\hline\n",
                  "\\multicolumn{", dim(x)[2] + 1, "}{l}",
                  "{\\footnotesize Continued on next page}\n",
                  "\\endfoot\n",
                  "\\endlastfoot\n")
add.to.row$command <- command

print (xtable (x), 
       add.to.row = add.to.row,
       tabular.environment = "longtable")


```

## Table with Alternate Colours

```{r table2, results='asis'}
rws <- seq(1, (nrow(x)-1), by = 2)
col <- rep("\\rowcolor[gray]{0.95}", length(rws))

print(xtable(x), booktabs = TRUE,
      add.to.row = list(pos = as.list(rws), command = col),
      tabular.environment = "longtable")

```

1 个答案:

答案 0 :(得分:0)

我最终能够使用pixidust包提出解决方案。

---
title: "Test"
header-includes:
   - \usepackage{fontspec}
   - \setmainfont{Arial}
   - \usepackage{fancyhdr}
   - \usepackage{booktabs} # For Colored rows in tables
   - \usepackage[table]{xcolor} # For Colored rows in tables
   - \usepackage{longtable}
output:
  pdf_document:
    latex_engine: xelatex
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Test Table

```{r table, results='asis',message=FALSE, warning=FALSE}

library(pixiedust)

custom_interfoot <- data.frame("Cont'd", 
                               "", "", "", "")

n_rows <- length(iris[,1])

x <- dust(iris,
          longtable = TRUE) %>%
  redust(custom_interfoot, part = "interfoot") %>%
  sprinkle (rows = c(1:n_rows), halign = "center") %>%
  sprinkle (bg_pattern = c ("#D6D6D6", "white")) 


print (x)



```