我在 R 中有以下(示例)数据汇总表,它有两个 ID 列,year
和 group
:
input <- as.data.frame(cbind(year = c(2000, 2000, 2001, 2001),
group = c(0 ,1 , 0 , 1),
count = c(5, 10, 6, 12),
shares = c(5/15, 10/15, 6/18, 12/18)))
# input
# year group count shares
# 1 2000 0 5 0.3333333
# 2 2000 1 10 0.6666667
# 3 2001 0 6 0.3333333
# 4 2001 1 12 0.6666667
我想将其作为表格导出到 latex/html 中,使用 group
ID 作为列拆分,如下所示:
| year | count | shares |
| | 0 | 1 | 0 | 1 |
| ---- | -- | --- | --- | --- |
| 2000 | 5 | 10 | .33 | .67 |
| 2001 | 6 | 12 | .33 | .67 |
R 中是否有使这成为可能的包?
到目前为止,我看过 Stargazer
,它似乎不支持这一点。
感谢您的帮助!
最佳答案
为此,我将 knitr
与 kableextra
结合使用。
你的例子是(我在这里使用 latex
输出,你可以使用 knitr::kable(format = "html")
调整/切换到 html
> ):
library(tidyverse)
library(kableExtra)
input %>%
gather(var, value, -year, -group) %>%
unite(group, c("var", "group"), sep = "_", remove = TRUE) %>%
spread(group, value) %>%
set_names("year", "0", "1", "0", "1") %>%
knitr::kable(escape = F, format = "latex") %>%
add_header_above(c(" ", "count" = 2, "shares" = 2))
latex
输出为:
\begin{tabular}{r|r|r|r|r}
\hline
\multicolumn{1}{c|}{ } & \multicolumn{2}{|c|}{count} & \multicolumn{2}{|c}{shares} \\
\cline{2-3} \cline{4-5}
year & 0 & 1 & 0 & 1\\
\hline
2000 & 5 & 10 & 0.3333333 & 0.6666667\\
\hline
2001 & 6 & 12 & 0.3333333 & 0.6666667\\
\hline
\end{tabular}
html
输出是:
<table>
<thead>
<tr>
<th style="border-bottom:hidden" colspan="1"></th>
<th style="border-bottom:hidden; padding-bottom:0; padding-left:3px;padding-right:3px;text-align: center; " colspan="2"><div style="border-bottom: 1px solid #ddd; padding-bottom: 5px;">count</div></th>
<th style="border-bottom:hidden; padding-bottom:0; padding-left:3px;padding-right:3px;text-align: center; " colspan="2"><div style="border-bottom: 1px solid #ddd; padding-bottom: 5px;">shares</div></th>
</tr>
<tr>
<th style="text-align:right;"> year </th>
<th style="text-align:right;"> 0 </th>
<th style="text-align:right;"> 1 </th>
<th style="text-align:right;"> 0 </th>
<th style="text-align:right;"> 1 </th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:right;"> 2000 </td>
<td style="text-align:right;"> 5 </td>
<td style="text-align:right;"> 10 </td>
<td style="text-align:right;"> 0.3333333 </td>
<td style="text-align:right;"> 0.6666667 </td>
</tr>
<tr>
<td style="text-align:right;"> 2001 </td>
<td style="text-align:right;"> 6 </td>
<td style="text-align:right;"> 12 </td>
<td style="text-align:right;"> 0.3333333 </td>
<td style="text-align:right;"> 0.6666667 </td>
</tr>
</tbody>
</table>
文档可以在 kableextra vignette 中找到
关于html - 具有第二个 ID 变量作为列拆分的数据框的 R 导出表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51817956/