【问题标题】:Knitr Kable to retain top left name in tableKnitr Kable 在表格中保留左上角的名称
【发布时间】:2019-10-15 12:47:08
【问题描述】:

在 R Markdown 中,当尝试使用 knitr::kable() 默认生成表时,它只保留行名和列名,但不保留左上角的单元格,在我的例子中是表名。

假设您有 iris 数据集,并且仅对 setosa 花执行 PCA,然后想要显示前 2 个 PC。即

set.pca <- prcomp(iris[which(iris[,5] == "setosa"),1:4])
t1 <- as.table(set.pca$rotation[,1:2]);t1
dimnames(t1) = list(Setosa=rownames(t1), colnames(t1))

t1 在这种情况下应该是:

Setosa                 PC1         PC2
  Sepal.Length -0.66907840  0.59788401
  Sepal.Width  -0.73414783 -0.62067342
  Petal.Length -0.09654390  0.49005559
  Petal.Width  -0.06356359  0.13093791

但我想在 Markdown 中使用 Kable() 将其放在此输出是

|             |        PC1|        PC2|
|:------------|----------:|----------:|
|Sepal.Length | -0.6690784|  0.5978840|
|Sepal.Width  | -0.7341478| -0.6206734|
|Petal.Length | -0.0965439|  0.4900556|
|Petal.Width  | -0.0635636|  0.1309379|

可以看出,“Setosa”不在此表中。你如何保持这个左上角的值?

【问题讨论】:

    标签: r markdown knitr


    【解决方案1】:

    这两个选项中的任何一个都应该适合您:

    library(knitr)
    library(kableExtra)
    library(reshape2)
    library(dplyr)
    library(magrittr)
    library(tidyr)
    
    data(iris)
    
    set.pca <- prcomp(iris[which(iris[,5] == "setosa"),1:4])
    t1 <- as.table(set.pca$rotation[,1:2]);t1
    dimnames(t1) = list(Setosa=rownames(t1), colnames(t1))
    
    # using library reshape2
    data.frame(t1) %>% reshape(idvar="Setosa", timevar="Var2", direction="wide") %>%
         kable() %>% kable_styling()
    

    # using library tidyr
    data.frame(t1) %>% spread(Var2, Freq) %>% kable() %>% kable_styling()
    

    在最新的tidyr 中有一个新功能,您也可以探索它,称为pivot_wider。我认为它旨在取代spread

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-13
      • 2019-03-27
      • 2021-02-06
      • 2021-12-20
      • 1970-01-01
      • 2018-04-20
      • 2016-01-28
      • 2016-01-27
      相关资源
      最近更新 更多