在R Markdown中创造Kable

时间:2018-02-15 10:27:11

标签: r r-markdown kable

如何将以下模型构造放入R markdown的kable中。

>modelTT <- glm(formula
           ,family=gaussian(link = "identity"), data=dataL_TT)

>regr_tab_NM(modelTT)

                                      Estimate Pr(>|t|)
        (Intercept)                    -2.6077  < 0.001
        Days_diff_Eff_Subm_2           -0.0114  < 0.001
        TR_BS_BROKER_ID_360_2           0.0344  < 0.001
        TR_BS_BROKER_ID_360_M           0.8551  < 0.001
        RURALPOP_P_CWR_2               -0.0083  < 0.001
        RURALPOP_P_CWR_M               -0.7106  < 0.001
        TR_B_BROKER_ID_360              0.0241  < 0.001
        TR_SCW_BROKER_ID_360           -0.0005  < 0.001
        PIP_Flag                        3.5838  < 0.001
        TR_BS_BROKER_INDIVIDUAL_720_2   0.0357  < 0.001
        TR_BS_BROKER_INDIVIDUAL_720_M  -0.0780  < 0.001
        Resolved_Conflictless5m         1.1547  < 0.001
        Resolved_Conflict5mTo1d         1.5352  < 0.001
        Resolved_Conflictafter1d        2.1279  < 0.001
        Priority_2Other                -1.1499  < 0.001

所以首先我开始   library(knitr)then kable(modelTT,.....)我不确定这是否正确。

1 个答案:

答案 0 :(得分:0)

通过保存要打印的对象,然后使用内联R函数(相对于块)来呈现表,可以使用kable()在R Markdown中直接从R函数打印表格内容。

要从模型中打印回归系数,需要确定包含该系数的特定对象并进行打印,而不是整个summary()对象。我们将使用lm()来说明一个简单的示例。

summary(lm(...))的输出对象是11个对象的列表,其中一个称为coefficientscoefficients对象包含回归斜率,标准误差,t和概率值。

以下代码可以另存为Rmd文件,并用knitr编织以将这些项目打印为kable()表。

---
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

Stackoverflow question [48804938](https://stackoverflow.com/questions/48804938/creating-kable-in-r-markdown) asked how to take output from a linear model and render it with kable in R Markdown. We'll run a `lm()` with the `mtcars` data frame and print the coefficients table with kable. 

```{r regression, echo = TRUE, warning = FALSE, eval = TRUE}
 library(knitr)
 fit <- lm(mpg ~ am + disp + wt, data = mtcars)
 theStats <- summary(fit)


```

At this point we can print the coefficients table with `theStats$coefficients` as the argument to the `kable()` function.

`r kable(theStats$coefficients)`

当我们将文档编织为HTML时,它将生成以下文档。

enter image description here