I have a question regarding converting spatial data in R and bringing it from R into QGIS.
I have a GeoTiff of Antarctic sea ice concentration, downloaded from the link below:
I want to extract the contour of the sea ice edge (defined as 15%), and then have this contour in a file type that I can open in QGIS and reproject for use in making other maps. My current understanding is that to do this, I would need to convert the contour to a spatial points df, and then convert that to a spatial polygons df which I would then be able to open as a shapefile in QGIS. However, I think I'm going wrong here as I cannot make the conversion with the below code - any suggestions?
**This is my current workflow:**
library(raster)
library(tidyverse)
library(sp)
library(sf)
#Load in sea ice geotiff
sic <- raster('Environmental_Data/SIC/AMSR2/asi-AMSR2-s3125-20220107-v5.4.tif')/1
plot(sic)
#Make all values over land NA
sic[sic>100] = NA
#Crop to make area smaller (I have a specific area of interest)
sic = crop(sic, extent(sic)*c(0.5,0.5,0,1))
plot(sic)
#Pull out the sea ice edge (15% contour) (this makes it a spatial lines df)
ie = rasterToContour(sic, levels=15)
#Convert to spatial points
ie.pt = as(ie, "SpatialPointsDataFrame") plot(ie.pt, add=T, pch=16, cex=0.4)
#Convert to spatial polygons
ie.pt_poly <-as(ie.pt, "SpatialPolygons")
#Then I get this error:
Error in as(ie.pt, "SpatialPolygons"):
no method or default for coercing “SpatialPointsDataFrame” to “SpatialPolygons”
I think this is what you are looking for.
library(terra)
r <- rast("asi-AMSR2-s3125-20221113-v5.4.tif")
# crop to the area of interest
e <- ext(-1975000, 1975000, 2e+05, 4350000)
re <- crop(r, e)
# get contour and save to file
v <- as.contour(re, levels=15)
writeVector(v, "contour_lines.shp")
Contours are normally lines (neither points nor polygons). But if you wanted a polygon you could do
x <- ifel(x <15 | x>100, NA, 1)
p <- as.polygons(x)
writeVector(p, "contour_polygons.shp")
Or, more generally, use terra::classify
to create regions before using as.polygons
.