1

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?

Peter.k
  • 1,475
  • 23
  • 40
  • Possible duplicate of [Reshape three column data frame to matrix ("long" to "wide" format)](https://stackoverflow.com/questions/9617348/reshape-three-column-data-frame-to-matrix-long-to-wide-format) – Brian Jun 25 '19 at 20:32
  • There are several ways to do this: https://stackoverflow.com/questions/9617348/reshape-three-column-data-frame-to-matrix-long-to-wide-format but which is the fastest and easiest for you depends on your data. These solutions assume you're filling with a 3rd variable, but you can just use `1` or `TRUE` for your use case. – Brian Jun 25 '19 at 20:32
  • 1
    As there's little description in the post, I think the commenters are missing that there are 2 operations happening, binning and reshaping. I'd encourage OP to tackle them separately, using `cut` for binning [as in this R-FAQ](https://stackoverflow.com/a/5570360/903061) and then reshaping as in Brian's links. (With the note that a 3rd variable isn't absolutely necessary, many of the solutions allow for an aggregate function, which could be used instead). – Gregor Thomas Jun 25 '19 at 20:45

0 Answers0