[GIS] Converting raster to im object for point process model covariate in R

rrasterraster-conversionspatstat

I am trying to convert a raster object to an .im object for use with a point process model in the spatstat package in R.
I begin by creating the raster from a tiff file using the raster() package. No problems there. I then proceed by cropping
the raster according to a given extent. Again, no problem there. I then specify a spatial window (owin) defined using the same extent.
Still no problems. When I then proceed to the final step of converting the raster to the im object using as.im(), the function runs and
the new im object is created, but it has somehow lost the pixel information that was contained in the original raster such that each
pixel now has the same value in the im object.

The date file used is here:
https://www.dropbox.com/s/n67djm3n0tfa6sx/MGVF_2001_30_arc_sec.tif?dl=0

I also have a pre-cropped file, which is much smaller in size, here:
https://www.dropbox.com/s/co2rsb4vbgn5kog/mgvf.2001.africa.tif?dl=0

And the R code is as follows:

library(raster)
library(spatstat)

# First set the geographic extent we'll be using
e <- extent(-20, 60, -40, 35)

# Then read in the Maximum Green Vegetation Fraction tiff and crop it
mgvf <- raster("MGVF_2001_30_arc_sec.tif")
mgvf.2001.africa <- crop(mgvf, e)

# Now let's create a window for in spatstat
SP.win <- as(e, "SpatialPolygons")
W <- as(SP.win, "owin")

# Finally, we create the .im object
mgvf.img <- as.im(X = "mgvf.2001.africa", W = W)

# Notice, there are no errors thrown. However, compare the plots below and see the loss of information:
plot(mgvf.2001.africa)
plot(mgvf.img)

Incidentally, I have tried the above as shown as well as trying to replace the NAs in the raster prior to converting to im. The result is the same.

Best Answer

If you would check help for as.im() you would notice that raster data type is not supported. We should thank @mdsumner for bringing up my old question (I do not remember the occasion that forced me to ask it - suppose it was just some testing and I wouldn't recall that question by myself). I used there a geostatsp package that provides needed functionality.

In your case it is just:

library(geostatsp)
mgvf.img <- as.im(mgvf.2001.africa)

Notice that if you don't want to use geostatsp (for no good reason), as.im() will work with matrices. So you will need to as.matrix(mgvf.2001.africa) and then rotate it (several times probably - I'm too sleepy to test it) with

rotate = function(mat) t(mat[nrow(mat):1,,drop=FALSE]) # mat - matrix

and then pass rotated matrix to as.im().