I have lots of points (coordinates) and I wish to store it as image matrix dx x dy
such as missing values mark as 0, otherwise put 1.
sample:
> s
[,1] [,2]
[1,] 452937.5 359878
[2,] 452937.0 359878
[3,] 452936.0 359878
[4,] 452936.0 359879
[5,] 452936.0 359880
[6,] 452935.5 359880
[7,] 452935.0 359880
[8,] 452934.0 359880
[9,] 452933.5 359880
[10,] 452933.0 359880
[11,] 452932.0 359880
[12,] 452931.5 359880
[13,] 452931.0 359880
[14,] 452930.0 359880
[15,] 452930.0 359881
[16,] 452929.0 359881
[17,] 452928.5 359881
[18,] 452928.0 359881
[19,] 452927.0 359881
[20,] 452926.5 359881
I have a function which can do this but is tremendously slow:
as.ImageMatrix <- function(mat) {
xmax = max(mat[,1]); ymax = max(mat[,2])
xmin = min(mat[,1]); ymin = min(mat[,2])
dx = xmax - xmin + 1
dy = ymax - ymin + 1
mval = NULL
for (ix in (1:dx)) { #ix=1
for (iy in (1:dy)) { #iy=1
#stop()
if (any(mat[,1] == (ix+xmin-1) & mat[,2] == (iy+ymin-1))) {
mval = c(mval, 1)
} else {
mval = c(mval, 0)
}
}
}
mi = matrix(mval, nrow = dx, byrow = T)
rownames(mi) <- c(xmin:xmax)
colnames(mi) <- c(ymin:ymax)
return(mi)
}
It gives 0/1 matrix which can be viewed using image
.
My question is: can I find something in any R libraries which makes it faster? I'm looking around rasters, matrices but can't find it.
Btw, when I use plot(s)
I get directly what I need, but how to store it in matrix with axis as dimensions?