替换 kable/R markdown 中的列名 [英] Replace column names in kable/R markdown

查看:56
本文介绍了替换 kable/R markdown 中的列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框有丑陋的列名,但是在我的报告中显示表格时,我想要它们的真实"名称,包括特殊字符 '('、换行符、希腊字母、重复名称等.

My data frame has ugly column names, but when displaying the table in my report, I want to their "real" names including special characters '(', new lines, greek letters, repeated names, etc.

是否有一种简单的方法可以替换 knitr 中的名称以允许这种格式?

Is there an easy way of replacing the names in knitr to allow such formatting?

我试图做的是抑制数据框名称的打印,并使用 add_header_above 以获得更好的名称和跨越多列的名称.我见过的一些建议说要使用:

What I have tried to do is suppress the printing of the data frame names and use add_header_above for better names and names that span several columns. Some advice I've seen says to use:

x <- kable(df)
gsub("<thead>.*</thead>", "", x) 

删除列名.这很好,但问题是当我随后 add_header_above 时,原始列名又回来了.如果我在 kable(...) 中使用 col.names=rep('',times=ncol(d.df)) 名称消失了,但行仍然存在,在我的新列名和表体之间留有空隙.这是一个代码块来说明:

to remove the column names. That's fine, but the issue is that when I subsequently add_header_above, the original column names come back. If I use col.names=rep('',times=ncol(d.df)) in kable(...) the names are gone but the row remains, leaving a gap between my new column names and the table body. Here's a code chunk to illustrate:

```{r functions,echo=T}
drawTable <- function(d.df,caption='Given',hdr.above){
require(knitr)
require(kableExtra)
require(dplyr)

hdr.2 <- rep(c('Value','Rank'),times=ncol(d.df)/2)
x <- knitr::kable(d.df,format='latex',align='c',
  col.names=rep('',times=ncol(d.df))) %>%     
kable_styling(bootstrap_options=c('striped','hover',
  'condensed','responsive'),position='center',
   font_size = 9,full_width=F)

x %>% add_header_above(hdr.2) %>%
  add_header_above(hdr.above)
}
```

```{r}
df <- data.frame(A=c(1,2),B=c(4,2),C=c(3,4),D=c(8,7))
hdr.above <- c('A2','B2','C2','D2')
drawTable(df,hdr.above = hdr.above)
```

推荐答案

我不确定您从哪里得到了替换行名的建议,但这似乎过于复杂.在 kable 中使用内置的 col.names 参数要容易得多.此解决方案适用于 HTML 和 LaTeX 输出:

I am not sure where you got the advice to replace rownames, but it seems excessively complex. It is much easier just to use the built-in col.names argument within kable. This solution works for both HTML and LaTeX outputs:

---
output:
  pdf_document: default
  html_document: default
---
```{r functions,echo=T}
require(knitr)

df <- data.frame(A=c(1,2),B=c(4,2),C=c(3,4),D=c(8,7))
knitr::kable(df, 
             col.names = c("Space in name",
                           "(Special Characters)",
                           "$\\delta{m}_1$",
                           "Space in name"))

```

PDF 输出:

HTML 输出:

这篇关于替换 kable/R markdown 中的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆