# Re: [R] help for cell2nb and queencell in spdep package

From: Roger Bivand <Roger.Bivand_at_nhh.no>
Date: Thu 04 Aug 2005 - 19:59:37 EST

On Wed, 3 Aug 2005, ecoinfo wrote:

> Dear Dr. Bivand and R-users,
> I have a 5 by 5 grid, say, location[1:5,1:5], and I want to know the
> indices of 8 neighbours of each cell. For example, for location[2,2], its
> neighbour coordinates are [1,1:3], [2,1], [2,3] and [3,1:3]. Sometimes I
> also need to remove edge effects (torus = TRUE).
> I have tried "cell2nb" function in your spdep package. Here's my example:
> > neigh <- cell2nb(5,5,type="queen",torus=T)
> > neigh
> Neighbour list object:
> Number of regions: 25
> Number of nonzero links: 200
> Percentage nonzero weights: 32
> Average number of links: 8
> > neigh[1]
> [[1]]
> [1] 2 5 6 7 10 21 22 25
> Is there way to index each element of neigh[1], i.e., the first is 2, the
> second is 5, ... ?

neigh is a list of integer vectors, so you can use standard indexing:

> neigh[[1]][1]

[1] 2

using double square brackets for accessing the list components, and single for the vector elements. I think this is what you are asking for, if not, please clarify. To find out which (row, column) address this corresponds to, look it up in the "region.id" attribute:

> attr(neigh, "region.id")[neigh[[1]][1]]
[1] "2:1"

> Could you also give me an example of the function "queencell(rowcol, nrow,
> ncol, torus=FALSE, rmin=1, cmin=1)"? What's a rowcol?

"rowcol: matrix with two columns of row, column indices"

The queencell function is used internally, but takes a single row matrix of (row, column) indices, and returns a matrix of (row, column) indices for the contiguous neighbours of that cell:

> queencell(matrix(c(1,1),1,2), 8, 8, TRUE)

row col

```[1,]   2   8
[2,]   1   8
[3,]   8   8
[4,]   2   1
[5,]   8   1
[6,]   2   2
[7,]   1   2
[8,]   8   2
```

attr(,"coords")
[1] 1 1

for your case on a torus.

Hope this helps,

Roger

> Thanks,
> Xiaohua
>
>

```--
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of