# Install the terra packageinstall.packages("terra")# Load the terra packagelibrary(terra)
Working with Rasters
Reading Raster Data
# Read a raster filer<-rast("path/to/raster/file.tif")# Print raster informationprint(r)
Creating Raster Data
# Create an empty raster with specific dimensionsr<-rast(nrows=100,ncols=100,xmin=0,xmax=10,ymin=0,ymax=10)# Assign values to the rastervalues(r)<-runif(ncell(r))
Writing Raster Data
# Write a raster to a filewriteRaster(r,"output_raster.tif",overwrite=TRUE)
# Read a vector filev<-vect("path/to/vector/file.shp")# Print vector informationprint(v)
Creating Vector Data
# Create a point vectorpoints<-vect(matrix(c(1,2,3,4,5,6),ncol=2),type="points")# Create a line vectorlines<-vect(matrix(c(1,2,3,4,5,6),ncol=2),type="lines")# Create a polygon vectorpolygons<-vect(matrix(c(1,2,3,4,5,6),ncol=2),type="polygons")
Writing Vector Data
# Write a vector to a filewriteVector(v,"output_vector.shp",overwrite=TRUE)
Raster-Vector Interactions
Extracting Raster Values
# Extract raster values at vector locationsvalues<-extract(r,v)
Rasterizing Vectors
# Rasterize a vectorr<-rasterize(v,r,field="attribute_name")
Vectorizing Rasters
# Convert raster to vectorv<-as.polygons(r)
Spatial Operations
Reprojecting Data
# Reproject a rasterr_proj<-project(r,"EPSG:4326")# Reproject a vectorv_proj<-project(v,"EPSG:4326")
Resampling Rasters
# Resample a rasterr_resample<-resample(r,r,method="bilinear")
Aggregating Rasters
# Aggregate a rasterr_agg<-aggregate(r,fact=2,fun="mean")
Masking Rasters
# Mask a raster with another raster or vectorr_masked<-mask(r,mask_layer)
Cropping Rasters
# Crop a rasterr_cropped<-crop(r,extent(0,5,0,5))
Visualization
Plotting Rasters
# Plot a rasterplot(r)
Plotting Vectors
# Plot a vectorplot(v)
Overlaying Rasters and Vectors
# Overlay a vector on a raster plotplot(r)plot(v,add=TRUE)