'Problem solving overlapping vectors in terra using terra::union

I have several polygons of habitat types, and depending on the ones I select I need to get the percentage of a country. The issue is that many polygons intersect, so I need to solve the intersections so that I don’t add the area twice and assume that the percentage of the country is higher than I should calculate.

library(sf)
library(terra)
hab1 <- sf::read_sf("/vsicurl/https://github.com/Sustainscapes/BiodiversityCounsil/raw/master/ForQuestion/Overdrev.shp") |>
  terra::vect()

hab2 <- sf::read_sf("/vsicurl/https://github.com/Sustainscapes/BiodiversityCounsil/raw/master/ForQuestion/Strandeng.shp") |>
  terra::vect()

Test1 <- terra::union(hab1, hab2)

This is not really working as it should, since the number of features in test1 is 21528, however the length of each variable is only 3

as seen in the following code, and that wont allow for subsetting:

length(Test1)
# [1] 21528
length(Test1$Overdrev)
# [1] 3
length(Test1$Strandeng)
# [1] 3

(a more elaborate version of this question is available here)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source