Search code examples
r-markdownkable

kable_styling inside a loop


I've been trying to use kable to create a table inside a loop. I found out that I need to encase the kable inside a print statement and have cat("\n"). With that I was able to print the table inside the loop. However, the format looks bad. How do I make the table inside the loop to be formatted correctly? How do I use kable_styling with print and kable inside a loop?

Here is my code

# function definition
test.kable <- function(filename){
rmarkdown::render(filename)
}

#test.rmd
```{r , echo=FALSE, results="asis"}
for (i in 1:2){
print(kable(head(iris)))
cat("\n")
}
```

```{r , echo=FALSE, results="asis"}
kable_styling(kable(head(iris)),c("striped","bordered","responsive"))
```  

#main r markdown in which I call the function
```{r,echo=FALSE,results='asis'}
test.kable("test.rmd")
```

Here is what it looks like in the html output. The first two iris tables doesn't have pretty format. How do I make them look like the last iris table?

html output

EDIT regarding answer

The accepted answer is useful as it tells me about css style that contains the table styling which I never pay attention. But if someone still wants to use kable_styling, I figured out you just need to do the following (credit to this answer):

```{r , echo=FALSE, results="asis"}
  for (i in 1:2){
  kable(head(iris)) %>%
  kable_styling("striped") %>% 
  htmltools::HTML() %>% 
  print
  cat("\n")
  }
```

Here is what the two tables look like with kable_styling: enter image description here


Solution

  • If you are able to add a .CSS file, we can style the table, since it's output is an HTML table in your example.

    ---
    title: "test"
    author: "John Doe"
    date: "18/11/2020"
    output: 
      html_document:
        css: styles.css
    ---
    
    #test.rmd
    ```{r , echo=FALSE, results="asis"}
    library(kableExtra)
    for (i in 1:2){
    print(kable(head(iris)))
    cat("\n")
    }
    ```
    
    ```{r , echo=FALSE, results="asis"}
    kable_styling(kable(head(iris)),c("striped","bordered","responsive"))
    ```  
    

    Here is the .css file titled styles.css in the same directory as the .Rmd

    table {
      margin: auto;
      border-top: 1px solid #666;
      border-bottom: 1px solid #666;
    }
    table thead th { border-bottom: 1px solid #ddd; }
    th, td { padding: 5px; }
    thead, tfoot, tr:nth-child(even) { background: #eee; }
    

    Which gives me the below output.

    enter image description here

    Here is where I looked for help, it even has a section about HTML tables and loops using kable.