Thursday, August 19, 2021

Work with Rsater data in R/RStudio

 There are several packages in R used in read and writing raster data (a GeoTIFF file). In this post, we will see a few notably tmap, ggplot, rgdal and raster.

The raster data I will use for this demonstration is this (n08_e007_3arc_v2.tif) Landsat8 image in .tif format. You can get such rasters from the USGS EarthExplorer platform or many other sources out there.

First things first is to install and import the packages if you don't have them already.

# packages <- c('raster', 'rgdal', 'ggplot2', 'tmap')
# install.packages(packages)

library(raster)
library(rgdal)
library(ggplot2)
library(tmap)


Reading and exploring the raster attributes

The read the raster file, we use the raster package. 

raster_img <- raster("C:/Users/Yusuf_08039508010/Desktop/Working_Files/IMG/n08_e007_3arc_v2.tif")

# Explore the loaded raster to get familiar with it...
class(raster_img) # 'RasterLayer' [package "raster"]
View(raster_img)
str(raster_img) # here we see that it only 1 band image
print(raster_img) # here we can find the CRS, Min/Max vaules, Extent, Dimensions etc
names(raster_img)
summary(raster_img)

By exploring the raster using the base R functions above, we already seen a lot of useful properties and information about our raster data. More metadata attributes can be accessed from the raster attribute using the @ slot symbol like this:-
crs(raster_img)
raster_img@crs
raster_img@extent
raster_img@file
raster_img@data
raster_img@rotated
raster_img@legend
raster_img@ncols
raster_img@nrows
raster_img@history
nlayers(raster_img)# Tells if the raster is "Single Layer (or Band) vs Multi-Layer (Band Geotiffs)"
The lines above are self explanatory, feel free to explore them and use them.


Visualizing the raster

Lets use the base R plot function to quickly visualize the image raster.

plot(raster_img)

The line above should yield this figure below:-


If we need more visualization options and power, then the packages we load from above will now come into play.




)




)








No comments:

Post a Comment