I am trying to use the xtable package to create a print-quality half matrix in R. I can create the full symetric matrix with no problem but when I extract only the lower triangle matrix, I get the error shown below.
library(Matrix)
datamat1<-tril(data1) #extract lower triangle
library(xtable)
options(xtable.floating = FALSE)
options(xtable.timestamp = "")
xtable(datamat1, digits = 3)
The error that I get is: "no applicable method for 'xtable' applied to an object of class "c('dtrMatrix', 'ddenseMatrix', 'triangularMatrix', 'dMatrix', 'denseMatrix', 'Matrix', 'xMatrix', 'mMatrix', 'Mnumeric', 'replValueSp')"
I know that converting the matrix to a half matrix also converts its class to dtrMatrix but there must be some way to export a lower triangle matrix in a publishable quality form. I have also tried using the 'zoo' package but without any luck. How can this be done.
Maybe keep the original matrix and just set the upper triangle to missing. Then you'll still have a regular matrix
object that xtable
can handle. The code below also shows a couple of other options besides xtable
for printing. (If you need the dtrMatrix
class object for further processing, you can of course just create that separately from the object created below for printing.)
---
title: "My Title"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo=FALSE)
library(tidyverse)
library(knitr)
library(gt)
library(xtable)
options(xtable.floating = FALSE)
options(xtable.comment = FALSE)
options(knitr.kable.NA="")
```
## Using `xtable`
```{r, results="asis"}
set.seed(3)
m = matrix(1:16 + rnorm(16), nrow=4)
m[upper.tri(m)] = NA_real_
xtable(m, digits=3)
```
## Using `knitr::kable`
```{r}
colnames(m) = 1:ncol(m)
rownames(m) = 1:nrow(m)
kable(m, row.names=TRUE, digits=3)
```
## Using the `gt` package
```{r}
gt(as_tibble(m),
rownames_to_stub=TRUE,
digits) %>%
fmt_missing(columns=everything(),
missing_text="") %>%
fmt_number(columns=everything(),
decimals=3)
```