xtable + knitr 设置列宽度 HTML

5

我该如何使用 xtable 包来设置 knitr (Rmd)代码块输出中各个列的宽度?

最小工作示例(MWE):

```{r setup, include=FALSE}
library(xtable)
```

```{r, results="asis", echo=FALSE}
print(xtable(mtcars[1:2, 1:2]), type="html", include.rownames=FALSE)
```

假设我想让列1宽2英寸,列2宽3英寸。
我不一定要使用xtable,但不知道还有哪些html表格包可以做到这一点。
1个回答

1
你可以更改xtable使用的CSS来格式化表格并更改列宽,但不允许更改单个列。
请参见http://nsaunders.wordpress.com/2012/08/27/custom-css-for-html-generated-using-rstudio/ 以下是一个示例:
将样式表(此处命名为custom.css)添加到与您的Markdown文件相同的文件夹中。
table {
   max-width: 95%;
   border: 1px solid #ccc;
 }

th {
  background-color: #000000;
    color: #ffffff;
    width: 100px;
}

td {
  background-color: #dcdcdc;
  width: 100px;
}

并设置选项使用此样式表。
```{r setup, include=FALSE}
library(xtable)
options(rstudio.markdownToHTML = 
       function(inputFile, outputFile) {      
       require(markdown)
       markdownToHTML(inputFile, outputFile, stylesheet='custom.css')   
      }
)

```

```{r, results="asis", echo=FALSE}
print(xtable(mtcars[1:2, 1:2]), type="html", include.rownames=FALSE)
```

也许可以通过修改 print.xtable 函数来获得更大的灵活性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接