【问题标题】:kable_styling inside a loop循环内的 kable_styling
【发布时间】:2020-11-19 01:33:52
【问题描述】:

我一直在尝试使用 kable 在循环中创建一个表。我发现我需要将 kable 包含在 print 语句中并使用 cat("\n")。这样我就可以在循环内打印表格。但是,格式看起来很糟糕。如何使循环内的表格正确格式化? 如何在循环内使用带有 print 和 kable 的 kable_styling?

这是我的代码

# 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")
```

这是它在 html 输出中的样子。前两个 iris 表没有漂亮的格式。如何让它们看起来像最后一个 iris 表?

编辑答案

接受的答案很有用,因为它告诉我包含我从不关注的表格样式的 css 样式。但是如果有人仍然想使用 kable_styling,我发现你只需要执行以下操作(感谢 answer):

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

下面是使用kable_styling 的两张表的样子:

【问题讨论】:

    标签: r-markdown kable


    【解决方案1】:

    如果您能够添加 .CSS 文件,我们可以为表格设置样式,因为在您的示例中它的输出是 HTML 表格。

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

    这是标题为 styles.css 的 .css 文件,与 .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; }
    

    这给了我以下输出。

    Here 是我寻求帮助的地方,它甚至有一个关于使用 kable 的 HTML 表和循环的部分。

    【讨论】:

    • 非常感谢您的回复。我看到了链接,但只使用 kable 部分查看循环,但没有阅读开头部分,因此错过了 css 样式。我很困惑为什么我的桌子看起来不一样。
    • 正确。由于kable_styling() 输出一个 kable 而 for 循环输出一个 html 表格
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    相关资源
    最近更新 更多