title: Creating a giant matrix for use in CARBayes without running out of memory
body: <p>I am trying to do an areal unit analysis using the package CARBayes. As part of the analysis, I am using the below code. my issue comes when I try to create the neighbour matrix with <code>nb2mat</code>. My sp object has 170,000 odd polygons in it so it can't make the matrix with the memory I have.</p>
  <pre><code>library(spdep)
  library(CARBayes)
  
  W.nb &lt;- poly2nb(sp)
  
  W &lt;- nb2mat(W.nb, style = &quot;B&quot;, zero.policy = TRUE)
  
  test &lt;- S.CARbym(case ~ covariate1),
               family = &quot;poisson&quot;,
               data = sp,
               W = W,
               burnin = 10000,
               n.sample = 30000,
               thin = 20)  
  </code></pre>
  <p>I found the below code in another thread to make a <code>bigmemory</code> matrix but CARBayes won't recognise it as a matrix.</p>
  <p>My question is, does anyone know a way to use <code>bigmemory</code> or <code>spam</code> /sparse matrix or something similar to create the matrix so that it can be used in the CARBayes package without throwing an error saying the <code>W</code> isn't a matrix.</p>
  <pre><code>
  my_listw2mat = function (listw) 
  {
    require(bigmemory)
    n &lt;- length(listw$neighbours)
    if (n &lt; 1) 
      stop(&quot;non-positive number of entities&quot;)
    cardnb &lt;- card(listw$neighbours)
    if (any(is.na(unlist(listw$weights)))) 
      stop(&quot;NAs in general weights list&quot;)
    #res &lt;- matrix(0, nrow = n, ncol = n)
    res &lt;- big.matrix(n, n, type='double', init=NULL)
    options(bigmemory.allow.dimnames=TRUE)
    
    for (i in 1:n) if (cardnb[i] &gt; 0) 
      res[i, listw$neighbours[[i]]] &lt;- listw$weights[[i]]
    if (!is.null(attr(listw, &quot;region.id&quot;))) 
      row.names(res) &lt;- attr(listw, &quot;region.id&quot;)
    res
  }
  
  my_nb2mat = function (neighbours, glist = NULL, style = &quot;W&quot;, zero.policy = NULL) 
  {
    if (is.null(zero.policy)) 
      zero.policy &lt;- get(&quot;zeroPolicy&quot;, envir = .spdepOptions)
    stopifnot(is.logical(zero.policy))
    if (!inherits(neighbours, &quot;nb&quot;)) 
      stop(&quot;Not a neighbours list&quot;)
    listw &lt;- nb2listw(neighbours, glist = glist, style = style, 
                      zero.policy = zero.policy)
    res &lt;- my_listw2mat(listw)
    attr(res, &quot;call&quot;) &lt;- match.call()
    res
  }
  
  W &lt;- my_nb2mat(W.nb, style = &quot;B&quot;, zero.policy = TRUE)
  
  test &lt;- S.CARbym(case ~ covariate1),
               family = &quot;poisson&quot;,
               data = sp,
               W = W,
               burnin = 10000,
               n.sample = 30000,
               thin = 20) 
  </code></pre>