如何防止 knitr 打印 ## 和矩阵 indices/row 数字?

How to prevent knitr from printing ## and matrix indices/row numbers?

假设我有一个矩阵,其中有一个 id 列每行不增加 1。

m <- matrix(c(1, "a", "c", 
              5, "g", "c", 
              4, "b", "c", 
              9, "g", "a"),
     ncol=3, byrow=TRUE)
colnames(m) <- c("id", "class", "type")

我试过用 rownames(m) <- NULLrownames(m) <- c() 重命名行,但我总是以最左边的行号结束输出:

     id  class type
[1,] "1" "a"   "c" 
[2,] "5" "g"   "c" 
[3,] "4" "b"   "c" 
[4,] "9" "g"   "a" 

此外,如果我在 knitr 中打印为 PDF,我会在旁边得到 ## 运行:

##      id  class type
## [1,] "1" "a"   "c" 
## [2,] "5" "g"   "c" 
## [3,] "4" "b"   "c" 
## [4,] "9" "g"   "a" 

我想打印一个只有我输入矩阵的数据的 pdf:

id  class type
"1" "a"   "c" 
"5" "g"   "c" 
"4" "b"   "c" 
"9" "g"   "a" 

您可以使用 knitr 包中的 kable

m <- matrix(
  c(1, "a", "c", 5, "g", "c", 4, "b", "c", 9, "g", "a"),
  ncol=3,
  byrow=TRUE
)

colnames(m) <- c("id", "class", "type")

knitr::kable(m)

# |id |class |type |
# |:--|:-----|:----|
# |1  |a     |c    |
# |5  |g     |c    |
# |4  |b     |c    |
# |9  |g     |a    |

您还可以阅读优秀的 kableExtra 软件包 here,这将为您提供一些很棒的格式设置选项。

N.B. My initial answer included casting as a data frame, which remains my usual workflow when creating tables. However as was pointed out, kable will happily accept a matrix as input.