Consider the following matrix
nr <span><-</span> nc <span><-</span> <span>6</span>
set.seed <span><-</span> <span>123</span>
m <span><-</span> matrix<span>(</span>sample<span>(</span>c<span>(</span>rep<span>(</span><span>0</span><span>,</span><span>9</span><span>),</span> <span>1</span><span>),</span>nr<span>*</span>nc<span>,</span> replace<span>=</span><span>T</span><span>),</span> nrow<span>=</span>nr<span>,</span> ncol<span>=</span>nc<span>)</span>
sum<span>(</span>m<span>)</span><span>/</span>length<span>(</span>m<span>)</span>
[1] 0.1667
dimnames<span>(</span>m<span>)</span> <span><-</span> list<span>(</span>letters<span>[</span><span>1</span><span>:</span>nr<span>],</span> letters<span>[</span><span>1</span><span>:</span>nc<span>])</span>
m
a b c d e f
a 0 0 0 0 0 1
b 0 0 0 1 0 1
c 0 0 0 0 0 0
d 0 0 0 0 0 0
e 1 1 0 0 0 0
f 0 0 0 1 0 0
This matrix can be coerced to a sparse matrix with
library<span>(</span><span>"Matrix"</span><span>)</span>
Loading required package: methods
Loading required package: lattice
M1 <span><-</span> as<span>(</span>m<span>,</span> <span>"dgCMatrix"</span><span>)</span>
M1
6 x 6 sparse Matrix of class "dgCMatrix"
a b c d e f
...