# Purpose of script: To reformat data created using GEE scripts
# to create predictors for modeling abundance

# Libraries ####

library(tidyverse)
library(sf)

# Settings ####

options(scipen = 999)
# Location where Google Earth Engine output is stored
fPath <- "C:\\GEE"

# Cleaning raw GPP data from GEE ####

# Compiling GPP data
gppData <- list.files(path = fPath, pattern = "DHI") %>%
  lapply(function(x) {
    oData <- read_csv(paste(fPath, x, sep = "")) %>%
      mutate(rteno = StateNum * 1000 + Route) %>%
      select(rteno, matches("cov|min|sum"))
    return(oData)
  }) %>%
  bind_rows(.) %>%
  pivot_longer(
    cols = colnames(.)[2]:colnames(.)[length(colnames(.))],
    names_to = "Measure",
    values_to = "GPP"
  ) %>%
  select(rteno, Measure, GPP) %>%
  pivot_wider(
    id_cols = rteno,
    names_from = Measure,
    values_from = GPP
  )

# Compiling land cover data
lcData <- list.files(path = fPath, pattern = "LC") %>%
  lapply(function(x) {
    oData <- read_csv(paste(fPath, x, sep = "")) %>%
      mutate(rteno = StateNum * 1000 + Route) %>%
      select(rteno, human, all) %>%
      mutate(impacted = round((human / all) * 100, 0)) %>%
      select(rteno, impacted)
    return(oData)
  }) %>%
  bind_rows(.)

# Exporting ####

write.csv(gppData, "C:\\GEE\\dhiData.csv", row.names = F)
write.csv(lcData, "C:\\GEE\\lcData.csv", row.names = F)