3

I would like to change the resolution of a raster. For example, let’s take this Landsat 7 images at ~ 30m resolution.

library(terra)
#> terra 1.5.21

f <- system.file("tif/L7_ETMs.tif", package = "stars")
r <- rast(f)

# 30m x 30m resolution
res(r)
#> [1] 28.5 28.5

plot(r, 1)

I can use aggregate() with an integer factor such as:

# 10 * 28.5
r2 <- aggregate(r, fact = 10)
res(r2)
#> [1] 285 285

plot(r2, 1)

My question is, how can I specify an exact resolution. For example, I would like to have a pixel resolution of 1.234 km (1234 m).

fact <- 1234 / 28.5
fact
#> [1] 43.29825

r3 <- aggregate(r, fact = fact)
res(r3)
#> [1] 1225.5 1225.5

plot(r3, 1)

The documentation says that fact should be an integer, so here it is flooring fact to 43.

res(aggregate(r, 43))
#> [1] 1225.5 1225.5

Any ways to have an exact resolution of 1234 m?

Created on 2022-04-28 by the reprex package (v2.0.1)

2
  • 1
    A raster has to be made of regularly sized cells. If your original data has dimensions that are not a multiple of the resolution you choose, then your cells will not equal the extent of the original raster. Putting a fractional number into aggregate implies that you want a fractional number of cells in your resulting raster, which doesn't really make sense. Of course, it should be possible if cropping were allowed, but that option doesn't seem to be included. I guess you could crop the raster to a multiple of fact then aggregate it? Apr 28, 2022 at 13:22
  • Thank you, @AllanCameron, for responding. This is where I am stuck. I do not mind cropping a bit, but I kind of lost here. Do you have any resources or guidance to provide? How can r be cropped using a factor? Would it be possible to create a grid of the desired resolution before and "translate" r into it? Apr 28, 2022 at 13:27

2 Answers 2

3

I came up with this solution which seems to give me what I need.

library(terra)
#> terra 1.5.21

f <- system.file("tif/L7_ETMs.tif", package = "stars")
r <- rast(f)

plot(r, 1)

r2 <- r
res(r2) <- 1234
r2 <- resample(r, r2)

plot(r2, 1)

res(r2)
#> [1] 1234 1234

Created on 2022-04-28 by the reprex package (v2.0.1)

2
  • 1
    I was about to post a very similar solution using resample, but this one is just as good! Apr 28, 2022 at 13:52
  • Thank you, @AllanCameron. Your previous answer guided me to approach this differently. Apr 28, 2022 at 13:53
1

I also propose (as described in the terra vignette) that you first aggregate the raster as close as possible and then resample. Resampling can be done e.g. using a template raster to guarantee correct crs, dimensions etc.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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