Knitr Kable 在 table 中保留左上角的名字
Knitr Kable to retain top left name in table
在 R Markdown 中,当默认情况下尝试使用 knitr::kable()
生成 table 时,它只保留行名和列名,但不保留左上角的单元格,在我的情况是 table 名称。
比如说你有鸢尾花数据集,只对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
但是因为我想使用 Kable()
将其放入 Markdown 中,所以输出是
| | 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”不在这个table中。你如何保持这个左上角的值?
这两个选项中的任何一个都适合您:
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
.
在 R Markdown 中,当默认情况下尝试使用 knitr::kable()
生成 table 时,它只保留行名和列名,但不保留左上角的单元格,在我的情况是 table 名称。
比如说你有鸢尾花数据集,只对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
但是因为我想使用 Kable()
将其放入 Markdown 中,所以输出是
| | 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”不在这个table中。你如何保持这个左上角的值?
这两个选项中的任何一个都适合您:
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
.