[R] Lattice nb/wlist help
David Winsemius
dwinsemius at comcast.net
Wed Apr 27 15:40:41 CEST 2011
On Apr 27, 2011, at 5:28 AM, Gary Nobles wrote:
> hi I am still tryingto do this, I have been working on this for a
> year but i
> have remained stuck...
>
> I have points at regular intervals but within an irregular window
>
> I need to make a nb weights matrix, then nb2wlist
Not sure I understand those terms ...
> conceptually a D8 neighbourhood something like this:
>
> 0000000
> 0000000
> 0011100
> 0011100
> 0011100
> 0000000
> 0000000
Certainly looks like a matrix
>
> but I also want another matrix like this (D24):
>
> 0000000
> 0111110
> 0111110
> 0111110
> 0111110
> 0111110
> 0000000
>
Looked at package raster and the raster objects can be converted to
matrices but do not accept the same operations with the row() and
col() functions, so ....
Convert the raster to a matrix. Calling it r1m in this case:
> as.matrix(r1)
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] NA NA NA NA NA NA NA
[2,] NA NA NA NA NA NA NA
[3,] NA NA 1 1 1 NA NA
[4,] NA NA 1 1 1 NA NA
[5,] NA NA 1 1 1 NA NA
[6,] NA NA NA NA NA NA NA
[7,] NA NA NA NA NA NA NA
#Create a 3 element wide square "sensing" function:
near1s <- function(r, c, mtx) !is.na(mtx[ ( r-1):min((r+1), NROW(mtx)) ,
(c-1):min(c+1,
NCOL(mtx)) ])
#Run it over your 'matrified' raster:
for (r in 1:NROW(r1m) ) {
for( c in 1:NCOL(r1m)){
newm[r,c] <- sum(near1s(r,c,r1m)) >0}}
newm
# Not run;
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 0 0 0 0 0 0 0
[2,] 0 1 1 1 1 1 0
[3,] 0 1 1 1 1 1 0
[4,] 0 1 1 1 1 1 0
[5,] 0 1 1 1 1 1 0
[6,] 0 1 1 1 1 1 0
[7,] 0 0 0 0 0 0 0
# Then convert it back to a raster
Somewhere along the line I dropped the use of row and col, so I guess
this might even work when appropriate modified for the test for sum
without converting and using the !is.na() function.
Trying that notion:
> for (r in 1:NROW(r1) ) {
+ for( c in 1:NCOL(r1)){
+ newm[r,c] <- sum(r1[( r-1):min((r+1), NROW(r1)) ,
(c-1):min(c+1, NCOL(r1)) ]) >0}}
Warning message:
In .doExtract(x, i, drop = drop) : some indices are invalid (NA
returned)
> newm
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] NA 0 0 0 0 0 0
[2,] 0 1 1 1 1 1 0
[3,] 0 1 1 1 1 1 0
[4,] 0 1 1 1 1 1 0
[5,] 0 1 1 1 1 1 0
[6,] 0 1 1 1 1 1 0
[7,] 0 0 0 0 0 0 0
The fix seems obvious.
--
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list