# 5.1 How to handle Vector Data

# 1. Install and load necessary packages
# First, we need to install some packages that help us load and display visual data
install.packages(c("sf", "ggplot2"))

# Load the libraries
library(sf)         # For handling spatial data
library(ggplot2)    # For visualization, from maps to plots

# 2. Load vector data
# R can handle vector data in formats like Shapefiles (.shp) or GeoJSON.

# Download example vector data
# Example: Using a sample dataset of natural Earth admin boundaries
url <- "https://naturalearth.s3.amazonaws.com/110m_cultural/ne_110m_admin_0_countries.zip"
download.file(url, "ne_countries.zip")
unzip("ne_countries.zip", exdir = "ne_countries")

# Read the Shapefile into R using `st_read` from `sf`
shapefile_path <- "ne_countries/ne_110m_admin_0_countries.shp"
countries <- st_read(shapefile_path)

# 3. Check the Metdata
# Check the structure of the loaded data and access the attribute data
head(countries)  # Inspect the first few rows of attribute data
summary(countries)  # Summary of attributes and geometry types

# 4. Visualize the data: Create a basic map
# Use ggplot2 to create a simple map of the countries
ggplot(data = countries) +
  geom_sf(fill = "lightblue", color = "black", size = 0.2) +
  labs(title = "World Map", subtitle = "Basic visualization of vector data") +
  theme_minimal()


# Select and plot specific attributes
# Example: Highlight a single country (e.g., Kenya)
Ghana <- countries[countries$NAME == "Kenya", ]
ggplot(data = countries) +
  geom_sf(fill = "gray90", color = "black", size = 0.2) +
  geom_sf(data = Ghana, fill = "green", color = "darkgreen", size = 0.5) +
  labs(title = "Highlighting Ghana", subtitle = "Example of subsetting spatial data") +
  theme_minimal()

