Unexpected behaviour when using extract on a SpatRaster object by lines

Viewed 41

I was about to produce some elevation transects when I noticed some weird behaviour I cannot explain, because the transects per se should not differ structurally. Using example data, t1 - the E-W-transect - produces 95 values using extract but t2 - the N-S-transect - only 2 values consisting of NA.

library(terra)
#> terra 1.6.7

filename <- system.file("ex/elev.tif", package="terra")

r <- rast(filename)
r
#> class       : SpatRaster 
#> dimensions  : 90, 95, 1  (nrow, ncol, nlyr)
#> resolution  : 0.008333333, 0.008333333  (x, y)
#> extent      : 5.741667, 6.533333, 49.44167, 50.19167  (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat WGS 84 (EPSG:4326) 
#> source      : elev.tif 
#> name        : elevation 
#> min value   :       141 
#> max value   :       547

# create transects
e <- ext(r)
t1 <- rbind(c(e[1], 49.8), c(e[2], 49.8)) |> vect("lines", crs = "epsg:4326")
t2 <- rbind(c(6.0, e[3]), c(6.0, e[4])) |> vect("lines", crs = "epsg:4326")

# inspect
plot(r)
plot(t1, add = TRUE)
plot(t2, add = TRUE)


# extract values by lines
t1_vals <- terra::extract(r, t1)

dim(t1_vals)
#> [1] 95  2
head(t1_vals)
#>   ID elevation
#> 1  1        NA
#> 2  1        NA
#> 3  1        NA
#> 4  1        NA
#> 5  1       402
#> 6  1       418

t2_vals <- terra::extract(r, t2)

dim(t2_vals)
#> [1] 2 2
head(t2_vals)
#>   ID elevation
#> 1  1        NA
#> 2  1        NA

I would expect a vector of length 90 for t2_vals$elevation, according to nrow(r).

What am I missing?

Edit:

touches = TRUE does not change the result returned by extract(), but exact = TRUE apparently does although I would not expect a change in behaviour here since y is not of polygon type (c.f. ?extract):

t1_vals <- terra::extract(r, t1, exact = TRUE)

dim(t1_vals)
#> [1] 95  3
head(t1_vals)
#>   ID elevation   fraction
#> 1  1        NA 0.01052632
#> 2  1        NA 0.01052632
#> 3  1        NA 0.01052632
#> 4  1        NA 0.01052632
#> 5  1       402 0.01052632
#> 6  1       418 0.01052632

t2_vals <- terra::extract(r, t2, exact = TRUE)

dim(t2_vals)
#> [1] 90  3
head(t2_vals)
#>   ID elevation   fraction
#> 1  1        NA 0.01111183
#> 2  1        NA 0.01111181
#> 3  1       515 0.01111179
#> 4  1       491 0.01111178
#> 5  1       469 0.01111176
#> 6  1       476 0.01111175
0 Answers
Related