I have a covertype raster layer which is categorical data (1,2,3...19), and I want to change its resolution, coordination system, column numbers and row numbers to fit with other raster layers. But after I did the resample with "ngb" method, it turned out to have continuous numbers, instead of discrete numbers.

The code is like:

newproj<-"+proj=utm +zone=47 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"
covertype1<-projectRaster(covertype, crs=newproj, res=30)
e<-extent(597568.9, 795028.9, 2340412, 2499892)
s<-raster(e, nrows=5316, ncols=6582, crs=newproj)
covertype2<-resample(covertype1, s, method="ngb")

I thought using method of "ngb" would not yield numbers different from the original raster layers, but "covertype2" has numbers like 10.00000023.

What is wrong here?


You also need to use a nearest neighbour method when reprojecting:

covertype1<-projectRaster(covertype, crs=newproj, res=30)

from ?projectRaster

method: method used to compute values for the new RasterLayer. Either
      'ngb' (nearest neighbor), which is useful for categorical
      variables, or 'bilinear' (bilinear interpolation; the default
      value), which is appropriate for continuous variables.

adding method="ngb" to your reprojection should fix that.


Without a reproducible example, it is difficult to say but I expect your problem is to do with the data type.

For example:


ras1 <- raster(matrix(sample(1:19, 100, replace=T), nrow = 10), ) # Make some example data (10 x 10 px)
ras2 <- raster(matrix(rep(1,16), nrow = 4)) # Make a smaller raster (4 x 4 px)
ras3 <- resample(ras1, ras2, method="ngb")

unique(ras1) # Only whole numbers
unique(ras3) # Only whole numbers

This works fine so without knowing more about your file it is difficult to answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.