Search code examples
rrastershapefileterra

Add a column to a shapefile using terra?


We have a shape file like this:

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

We can add a field or a column like this:

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

However, I want to add a column from:dat, column my, to all corresponding names in NAME_2 in v

dat=structure(list(ec = c("Diekirch", "Redange"), med.x = c(7, 8), 
                   co.x = c(113L, 590L), my = c(3, 5), co.y = c(113L, 590L), 
                   per = c(3, 9)), row.names = 1:2, class = "data.frame")

Solution

  • You can use left_join from tidyterra package to join a data frame to shapefile like

    library(terra)
    library(tidyterra)
    
    v <- system.file("ex/lux.shp", package="terra") |> vect()
    
    dat=structure(list(ecoregion = c("Diekirch", "Redange"), med.x = c(7, 8), 
                       co.x = c(113L, 590L), my = c(3, 5), co.y = c(113L, 590L), 
                       per = c(3, 9)), row.names = 1:2, class = "data.frame")
    
    left_join(v, dat, by = c("NAME_2" = "ecoregion"))
    

    You can also use merge function from terra package like

    merge(v, dat, all.x=TRUE, by.x=c('NAME_2'), by.y=c('ecoregion'))