---
title: "Arithmetic"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Arithmetic}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
# Enable densification for vignette examples
old_options <- options(dbMatrix.allow_densify = TRUE)
```
```{r setup}
library(dbMatrix)
```
## dbMatrix arithmetic
`dbMatrix` objects support `Arith` and `Ops` operations. We will demonstrate how to perform arithmetic operations on `dbSparseMatrix` objects.
**Note on sparse matrices:** a `dbSparseMatrix` stores only non-zero values.
Operations that turn 0 into something else, such as `x + 1`, `1 / x`, `exp(x)`
or `x == 0`, first fill in the zeros, which can use a lot of space for large
matrices. This only happens when `options(dbMatrix.allow_densify = TRUE)` is
set; otherwise these operations give an error. `log()`, `log2()` and `log10()`
are the exception: they transform only the stored values and leave zeros at 0.
See `?dbMatrix_options` and `?Math,dbMatrix-method`.
Please report problems on [GitHub](https://github.com/dbverse-org/dbmatrix-r/issues).
### Create test data
Let's create a simple sparse matrix for demonstration:
```{r}
# Create a sparse matrix
set.seed(42)
dgc <- Matrix::rsparsematrix(100, 50, density = 0.1, rand.x = function(n) rpois(n, 5) + 1)
rownames(dgc) <- paste0("gene_", seq_len(100))
colnames(dgc) <- paste0("cell_", seq_len(50))
dplyr::glimpse(dgc)
```
The matrix contains 100 rows (genes) and 50 columns (cells). Like most single-cell RNA-seq data, the matrix is sparse.
### Create a dbMatrix object
Let's create a `dbSparseMatrix` object from the above `dgc` object.
```{r}
# Note: by default the constructor creates a dbMatrix object in-memory
con <- DBI::dbConnect(duckdb::duckdb(), ":memory:")
dbsm <- dbMatrix(
value = dgc,
con = con,
name = "test_matrix",
class = "dbSparseMatrix",
overwrite = TRUE
)
# preview the object
dbsm
```
### Scalar Arithmetic
`dbMatrix` emulates scalar arithmetic in the `Matrix` package.
Note: Addition or subtraction with non-zero addends on a `dbSparseMatrix` results in a `dbDenseMatrix`.
```{r}
dbsm + 1
dbsm * 100
```
### Matrix Arithmetic
`dbMatrix` also supports matrix arithmetic for `dbMatrix` objects that are [conformable](https://en.wikipedia.org/wiki/Conformable_matrix).
```{r}
dbsm + dbsm
```
### Matrix Multiplication
#### Hadamard product
```{r}
dbsm * dbsm
```
#### Matrix product
The matrix product (`%*%`) is not supported yet.
### Cleanup
```{r}
DBI::dbDisconnect(con, shutdown = TRUE)
options(old_options)
```
### Session Info
```{r}
sessionInfo()
```
.