2

I am trying to convert a matrix (myMat) to raster data (myRas); however, I am not sure why this rotates all of a sudden. This can be easily fixed by 90-degree rotation using t() but, I will be grateful if someone explains why this unwanted rotation happens all the time?! and if there is a way to prevent it?

set.seed(23022019)
library(raster)
library(RColorBrewer)

#myMat
myMat<-matrix(runif(3*3), ncol=3) 
image((myMat), col=rev(brewer.pal(9,"RdYlBu")))

#myRas
myRas <- raster(myMat)
image((myRas), col=rev(brewer.pal(9,"RdYlBu")))

enter image description here

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
Majid
  • 1,836
  • 9
  • 19
  • 1
    @www : this is not a duplicate of https://stackoverflow.com/questions/14513480/convert-matrix-to-raster-in-r ---- even if the title suggests that. That question is about creating a RasterLayer from a list with x, y, and z vectors – Robert Hijmans Feb 23 '19 at 21:24
  • 1
    @RobertHijmans Sure. Let me re-open it. – www Feb 23 '19 at 21:25

1 Answers1

4

I would argue that myRas is not rotated; and that image(myMat) is rotated. See below.

library(raster) 
myMat<-matrix(1:9, ncol=3, byrow=TRUE)
myRas <- raster(myMat)

par(mfrow=c(1,2))
image(myMat, col=terrain.colors(9), main="image(myMat)")
plot(myRas,  col=terrain.colors(9), main="plot(raster(myMat))")
text(myRas)

enter image description here

myMat
#     [,1] [,2] [,3]
#[1,]    1    2    3
#[2,]    4    5    6
#[3,]    7    8    9

What happens is that image(myMat) read the values row-wise, and fills the values column-wise, from bottom to top. You may desire that, but it is a rotation. In contrast, raster(myMat) keeps the values in the same order.

The help from graphics::image explains why it displays the values like this; even if it may be very difficult to follow. If you provide a matrix with values, but not x and y coordinates, the first argument (x) is "used instead of z for convenience". This will give you equally spaced values from 0 to 1 for x and y, and the (z) values are assumed to be in ascending order (starting at the lower left corner and going row-wise!).

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
  • This is one a subtle point of matrix to raster conversion rules. I do not think that in clearly mentioned in their help documents. – Majid Feb 24 '19 at 01:08
  • 1
    I expanded my answer to explain what graphics::image does. As for `raster`, I do not know what one would say about unexpected things that do *not* happen. – Robert Hijmans Feb 24 '19 at 18:40