Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Arithmetic operations are faster for vectors in R #9

Closed
kadyb opened this issue May 20, 2021 · 0 comments
Closed

Arithmetic operations are faster for vectors in R #9

kadyb opened this issue May 20, 2021 · 0 comments

Comments

@kadyb
Copy link
Owner

kadyb commented May 20, 2021

One interesting observation is that arithmetic operations (e.g. computing NDVI) are faster for vector/matrices than for raster objects (stars or SpatRaster) in R. At this moment, this is especially true for the terra package, where it is probably better to convert the raster to a matrix, perform calculations, and then assign the results back to the raster object.

library(stars)
library(terra)

ndvi = function(red, nir) {(nir - red) / (nir + red)}

rasters = list.files("data/LC08_L1TP_190024_20200418_20200822_02_T1/",
                     pattern = "\\.TIF$", full.names = TRUE)


### calculate NDVI using 'stars' objects
ras = read_stars(rasters, along = 3, proxy = FALSE)

red = adrop(ras[,,,6])
nir = adrop(ras[,,,7])

system.time(ndvi(red, nir))
#>  user  system elapsed
#> 0.756   0.711   1.467


### calculate NDVI using 'SpatRaster' objects
ras = rast(rasters)
ras = ras * 1

red = ras[[6]]
nir = ras[[7]]

system.time(ndvi(red, nir))
#>  user  system elapsed
#> 4.141   3.320   7.462


### calculate NDVI using vectors
vred = values(red, mat = FALSE)
vnir = values(nir, mat = FALSE)

system.time(ndvi(vred, vnir))
#>  user  system elapsed
#> 0.558   0.209   0.767


### calculate NDVI using vectors
### and assign values to new 'SpatRaster'
new = rast(red)
system.time(new <- setValues(new, ndvi(vred, vnir)))
#>  user  system elapsed
#> 0.989   0.768   1.758
@kadyb kadyb closed this as completed May 20, 2021
@kadyb kadyb mentioned this issue May 20, 2021
7 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant