2

I've been rewriting an R script so it uses terra instead of raster and other packages, and I've managed to do it all except for one painfully simple task - adding an ID column to a SpatVector.

My code up to that point is simply:

AOI_path <- "N:/R/AOI_polygon.shp"
AOI <- project(vect(AOI_path), "epsg:27700")
AOI <- buffer(AOI, -15)

I can easily do what I originally did, and then convert the result into a SpatVector, as below:

AOI <- st_transform(read_sf(AOI_path), crs=27700)
AOI <- st_buffer(AOI, -15)
AOI <- AOI[!st_is_empty(AOI),]
AOI <- mutate(AOI, ID=row_number())
AOI_vect <- vect(AOI)

But I'd prefer to do it all within terra if possible. I've tried multiple methods like: AOI$ID <- 1:nrow(AOI), or making a dataframe and adding it to the SpatVector, but I usually get this error: Error: [[[<-,SpatVector cannot set these values.

2 Answers 2

5

If AOI is of class SpatVector, your first attempt should work without problems:

library(terra)
#> terra 1.6.7

v <- system.file("ex/lux.shp", package="terra") |> vect()

class(v)
#> [1] "SpatVector"
#> attr(,"package")
#> [1] "terra"

v[["ID_new_v1"]] <- 1:nrow(v)
v$ID_new_v2 <- 1:nrow(v)

v
#>  class       : SpatVector 
#>  geometry    : polygons 
#>  dimensions  : 12, 8  (geometries, attributes)
#>  extent      : 5.74414, 6.528252, 49.44781, 50.18162  (xmin, xmax, ymin, ymax)
#>  source      : lux.shp
#>  coord. ref. : lon/lat WGS 84 (EPSG:4326) 
#>  names       :  ID_1   NAME_1  ID_2   NAME_2  AREA   POP ID_new_v1 ID_new_v2
#>  type        : <num>    <chr> <num>    <chr> <num> <int>     <int>     <int>
#>  values      :     1 Diekirch     1 Clervaux   312 18081         1         1
#>                    1 Diekirch     2 Diekirch   218 32543         2         2
#>                    1 Diekirch     3  Redange   259 18664         3         3

Created on 2022-08-17 by the reprex package (v2.0.1)

0
2

Here is an alternative.

v$ID <- seq.int(nrow(v))

Your Answer

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

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