# What a shapefile loses: names, times and types
# https://tidyecology.com/posts/what-a-shapefile-loses/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-10-14

## ---- setup ----
library(sf)
library(ggplot2)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          axis.text        = element_text(colour = te_body))
}

set.seed(20260812)
n <- 24

# the plots were visited during the working day, centred on mid-morning
hours <- (11 + rnorm(n, 0, 2.1)) %% 24

field <- data.frame(
  site_code           = sprintf("S%02d", seq_len(n)),
  browse_index_spring = round(runif(n, 0, 1), 3),
  browse_index_autumn = round(runif(n, 0, 1), 3),
  canopy_cover_class  = factor(sample(c("low", "medium", "high"), n, TRUE),
                               levels = c("low", "medium", "high"),
                               ordered = TRUE),
  visit_time          = as.POSIXct("2026-05-01", tz = "UTC") + 3600 * hours,
  browsed             = sample(c(TRUE, FALSE), n, TRUE),
  soil_ph             = round(runif(n, 4.2, 7.8), 2),
  stringsAsFactors    = FALSE)
field$soil_ph[c(4, 17)] <- NA

plots <- st_as_sf(cbind(field,
                        x = 400000 + runif(n, 0, 8000),
                        y = 5050000 + runif(n, 0, 8000)),
                  coords = c("x", "y"), crs = 32634)
str(field$canopy_cover_class)

## ---- write ----
dir_out <- file.path(tempdir(), "deposit")
dir.create(dir_out, showWarnings = FALSE)
shp  <- file.path(dir_out, "plots.shp")
gpkg <- file.path(dir_out, "plots.gpkg")

st_write(plots, shp,  quiet = TRUE, delete_dsn = TRUE)
st_write(plots, gpkg, quiet = TRUE, delete_dsn = TRUE)

from_shp  <- st_read(shp,  quiet = TRUE)
from_gpkg <- st_read(gpkg, quiet = TRUE)

## ---- geometry ----
c(coordinates = identical(st_coordinates(plots), st_coordinates(from_shp)),
  crs         = st_crs(plots) == st_crs(from_shp))

## ---- names ----
nm <- setdiff(names(from_shp), "geometry")
data.frame(deposited = setdiff(names(plots), "geometry"), shapefile = nm)

## ---- seasons ----
nm[2:3]

## ---- dollar ----
c(spring_column_found = !is.null(from_shp$browse_index_spring),
  time_column_found   = !is.null(from_shp$visit_time))

## ---- classes ----
cls <- function(z) sapply(st_drop_geometry(z), function(v) class(v)[1])
data.frame(column     = names(cls(plots)),
           deposited  = unname(cls(plots)),
           shapefile  = unname(cls(from_shp)),
           geopackage = unname(cls(from_gpkg)))

## ---- clock ----
recovered <- st_drop_geometry(from_shp)[[5]]
c(class = class(recovered)[1], distinct_values = length(unique(recovered)))

## ---- activity ----
circ_mean <- function(h) {
  a <- 2 * pi * h / 24
  (atan2(mean(sin(a)), mean(cos(a))) %% (2 * pi)) * 24 / (2 * pi)
}
circ_r <- function(h) {
  a <- 2 * pi * h / 24
  sqrt(mean(sin(a))^2 + mean(cos(a))^2)
}
night <- function(h) mean(h < 6 | h >= 18)

after_h <- rep(0, n)   # midnight, for every record
round(c(mean_hour_before = circ_mean(hours),
        mean_hour_after  = circ_mean(after_h),
        r_before         = circ_r(hours),
        r_after          = circ_r(after_h),
        night_before     = night(hours),
        night_after      = night(after_h)), 3)

## ---- fig-clock ----
clock <- rbind(
  data.frame(hour = hours,   panel = "as deposited"),
  data.frame(hour = after_h, panel = "read back from the shapefile"))
clock$panel <- factor(clock$panel, levels = unique(clock$panel))
# the radius separates overlapping points and carries no information
clock$rad   <- ave(seq_len(nrow(clock)), clock$panel, FUN = seq_along)

ggplot(clock, aes(x = hour, y = 0.32 + 0.03 * rad)) +
  geom_point(aes(colour = panel), size = 2.2, alpha = 0.9) +
  facet_wrap(~ panel) +
  coord_polar(theta = "x", start = 0) +
  scale_x_continuous(limits = c(0, 24), breaks = seq(0, 21, 3)) +
  scale_y_continuous(limits = c(0, 1.12), breaks = NULL) +
  scale_colour_manual(values = c(te_forest, te_rust)) +
  labs(x = NULL, y = NULL,
       title = "The same visits, before and after the deposit") +
  theme_datasheet() +
  theme(legend.position = "none",
        panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
        strip.text = element_text(colour = te_ink, face = "bold"))

## ---- missing ----
c(na_deposited = sum(is.na(field$soil_ph)),
  na_shapefile = sum(is.na(from_shp$soil_ph)),
  na_geopackage = sum(is.na(from_gpkg$soil_ph)))

## ---- fig-types ----
tab <- data.frame(
  column = rep(names(cls(plots)), 3),
  format = rep(c("deposited", "shapefile", "GeoPackage"), each = 7),
  class  = c(unname(cls(plots)), unname(cls(from_shp)), unname(cls(from_gpkg))))
tab$format <- factor(tab$format,
                     levels = c("deposited", "shapefile", "GeoPackage"))
tab$column <- factor(tab$column, levels = rev(names(cls(plots))))
tab$changed <- tab$class != rep(unname(cls(plots)), 3)

ggplot(tab, aes(x = format, y = column)) +
  geom_tile(aes(fill = changed), colour = te_paper, linewidth = 1.4) +
  geom_text(aes(label = class), size = 3.1, colour = te_ink) +
  scale_fill_manual(values = c(`FALSE` = te_line, `TRUE` = te_gold)) +
  labs(x = NULL, y = NULL,
       title = "Where the attribute table changes class") +
  theme_datasheet() +
  theme(legend.position = "none",
        panel.grid.major = element_blank())

## ---- dictionary ----
dictionary <- data.frame(
  column = c("canopy_cover_class", "visit_time", "browsed"),
  type   = c("ordered factor", "POSIXct, UTC", "logical"),
  detail = c(paste(levels(field$canopy_cover_class), collapse = " < "),
             "time of day is the analysis variable",
             "TRUE means browsing seen"))
dictionary

## ---- rebuild ----
lv <- strsplit(dictionary$detail[1], " < ")[[1]]
rebuilt <- from_gpkg
rebuilt$canopy_cover_class <- factor(rebuilt$canopy_cover_class,
                                     levels = lv, ordered = TRUE)

c(levels_from_gpkg = paste(levels(factor(from_gpkg$canopy_cover_class)),
                           collapse = " < "),
  levels_rebuilt   = paste(levels(rebuilt$canopy_cover_class), collapse = " < "))
