Search code examples
rpdfprintingknitrindices

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


Lets say I have a matrix where there's an id column that doesn't go up by 1 with each row.

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")

I've tried renaming the rows with rownames(m) <- NULL or rownames(m) <- c() but I always end up with an output that has the row numbers on the very left:

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

Further more, if I print to PDF in knitr, I get ## running down the side:

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

I would like to print a pdf that just has the data that I entered into the matrix:

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

Solution

  • You can use kable from the knitr package.

    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    |
    

    enter image description here

    You could also read up on the excellent kableExtra package here, which will allow you some great formatting options.

    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.