[R-sig-eco] neighbourhood in a grid

Marc Taylor marchtaylor at gmail.com
Fri Nov 7 13:52:54 CET 2014


Hi Monica,

I did something similar in the past, where I had to find the neighboring
matrix positions for each position. I think I have adapted the code
correctly to wraparound  - what I think you mean by a toroid grid (i.e.
left of column 1 is column 6 in your example). The following code gives you
the position numbers of the neighboring cells and then summarizes all
neighbors in 4 directions:

# populated toroidal grid
M <- matrix(c(1,1,1,1,2,3,1,3,2,1,1,1,1,1,1,4,1,1), 3, 6, byrow=TRUE)
M

#make results data.frame
grd <- cbind(pos=seq(M), expand.grid(row=seq(nrow(M)), col=seq(ncol(M))))
grd$val <- c(M)
head(grd)

#Get neighbors
pos <- array(grd$pos, dim=dim(M))
#down
down <- pos*NaN
down[-nrow(pos),] <- pos[-1,]
down[nrow(pos),] <- pos[1,]
grd$down.pos <- c(down)
grd$down.val <- grd$val[grd$down.pos]
#left
left <- pos*NaN
left[,-1] <- pos[,-ncol(pos)]
left[,1] <- pos[,ncol(pos)]
grd$left.pos <- c(left)
grd$left.val <- grd$val[grd$left.pos]
#up
up <- pos*NaN
up[-1,] <- pos[-nrow(pos),]
up[1,] <- pos[nrow(pos),]
grd$up.pos <- c(up)
grd$up.val <- grd$val[grd$up.pos]
#right
right <- pos*NaN
right[,-ncol(pos)] <- pos[,-1]
right[,ncol(pos)] <- pos[,1]
grd$right.pos <- c(right)
grd$right.val <- grd$val[grd$right.pos]

# summarize neighbors
grd$neighbors <- paste(grd$down.val, grd$left.val, grd$up.val,
grd$right.val, sep=",")
grd


I hope that helps.

Cheers, Marc


On Fri, Nov 7, 2014 at 12:53 PM, monica abrudan <monica.abrudan at gmail.com>
wrote:

> Dear all,
>
> I have a squared, toroidal grid populated by individuals of different types
> (number of types=n). All cells of the grid are populated. A simplified
> version of my grid, with dimensions 6x3 and n=4, looks like this
> [1 1 1 1 2 3;
>  1 3 2 1 1 1;
>  1  1 1 4 1 1]
>
> I want to check whether a type has a preference for any other type, that
> is, is it more likely that a type i is neighbouring type j, than it is
> neighbouring type k? In my example, type 3 is preferring more type 2 than
> it is preferring type 4.
>
> Is there a function or package in R that would deal with this problem? Or
> could you suggest an algorithm for solving this problem? Thank you
>
> Monica
>
>         [[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-ecology mailing list
> R-sig-ecology at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-ecology
>

	[[alternative HTML version deleted]]



More information about the R-sig-ecology mailing list