potatopainting
potatopainting

Reputation: 103

creating flextables through a for loop for pdf output

I am having trouble creating a flextable within a list of dataframes.

I have tried making the flextable as a function and then run this function through a for loop but I am not getting any output in my 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
```

Upvotes: 1

Views: 821

Answers (1)

Greg
Greg

Reputation: 3660

How about this:

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

Upvotes: 1

Related Questions