rasterToPoints in R does not return integer values
I am trying to convert a raster into a spatial point data frame using:
mypts <- rasterToPoints(myraster, spatial=T)
The input raster 'myraster' takes only integer values: 1,2, 3, 4, 5. But then the output
mypts@data has non-integer values such as 4.638932.
My temporary solution is to do a simple rounding up:
mydata <- round(mypts@data) # deal with floating points - temporary solution
I did some search suggesting the issue is that the converted spatial points are not positioned at the center of the pixel. I guess this has something to do with the extent. Does anyone have a suggested solution for this? Thanks.
I think your assumption is wrong. If you get values like
4.638932then the values of the raster are not integer. See these examples.
library(raster) r <- raster(ncol=36, nrow=18, vals=1:(18*36)) x <- rasterToPoints(r, spatial=T) head(x, 3) # layer #1 1 #2 2 #3 3
rr <- sqrt(r) xx <- rasterToPoints(rr, spatial=T) head(xx, 3) # layer #1 1.000000 #2 1.414214 #3 1.732051
To check with your data, you could do the equivalent of this (round the raster values)
rrr <- round(rr) xxx <- rasterToPoints(rrr, spatial=T) head(xxx, 3) # layer #1 1 #2 1 #3 2
It has nothing to do with the centers of the cells or the extent.