## Process the Copernicus Global Land Cover data 

# Load packages 
library(terra)
library(dplyr)
library(purrr)

# Check w/d and List file names 
files <- list.files()

# Set the desired resolution 
# 0.1° x 0.1° resolution
new_res <- c(0.25, 0.25)  

# Extract the year of the raster 
year <- substr(files, 28, 31)

# Extract the land cover type 
land <- substr(files, 37, nchar(files))
dash_pos <- regexpr("-", land)
land <- substr(land, 1, dash_pos - 1)

# Process the rasters 
result <- map(files, ~{
  rast1 <- rast(.x)
  template <- rast(ext(rast1), res = new_res, crs = crs(rast1))
  r_resampled <- resample(rast1, template, method = "bilinear")
  r_resampled_df <- as.data.frame(r_resampled, xy = TRUE)
})

# Merge to one dataframe and rename the columns to the land types 
result <- reduce(result, left_join, by = c("x", "y"))
colnames(result) <- c("x", "y", land)

# Crop to Europe 
result <- result %>% filter(x > -31.4 & x < 62 & y > 34.4 & y < 82)

# Save 
readr::write_rds(result, "copernicus_global_land_use_2019_0.25.rds")














