通过for循环为PDF输出创建弹性表

时间:2019-10-09 17:01:11

标签: r r-markdown flextable

我无法在数据帧列表中创建弹性表。

我尝试将flextable用作函数,然后通过for循环运行此函数,但我的pdf中没有任何输出。

---
title: "Cut"
author: "Question"
date: "10/9/2019"
output: pdf_document
---

```{r setup, include=FALSE}

library(flextable)

df <- data.frame("Item"=c("A","B","C","A","B","C"), "Qty"=c(5,10,15,20,25,30), "Location" = c("NY", "NJ","NY", "NJ","NY", "NJ"))


chunk <- 2
n <- nrow(df)
r  <- rep(1:ceiling(n/chunk),each=chunk)[1:n]
d <- split(df,r)

Table_func <- function(the_table){
  Table = flextable(the_table)
  Table <- align(Table,  align = "center", part = "all")
}

Table_out = c()

for(i in seq_along(d)){

  Table_out[[i]] = Table_func(as.data.frame(d[[i]]))

}

Table_out
```

1 个答案:

答案 0 :(得分:0)

如何?

```{r echo = FALSE, results = 'asis'}
library(flextable)
library(knitr)
library(dplyr)

df <- data.frame("Item"=c("A","B","C","A","B","C"), "Qty"=c(5,10,15,20,25,30), "Location" = c("NY", "NJ","NY", "NJ","NY", "NJ"))

chunk <- 2
n <- nrow(df)
r  <- rep(1:ceiling(n/chunk),each=chunk)[1:n]
d <- split(df,r)

results <- character()
for(i in seq_along(d)){

  tb <- d[[i]] %>%
    as.data.frame() %>%
    flextable() %>%
    align(align = "center", part = "all")

  results <- c(results, knit_print(tb))

}

asis_output(results)
```