---
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:** Some operations with zero values are not yet supported with dbMatrix objects. In addition, certain arithmetic operations between `dbMatrix` objects are also not yet supported. We welcome user feedback and reporting issues on the [Github page ](https://github.com/dbverse-org/dbmatrix-r/).
### 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
TODO
### Cleanup
```{r}
DBI::dbDisconnect(con, shutdown = TRUE)
options(old_options)
```
### Session Info
```{r}
sessionInfo()
```