Enhance area change KPI calculation to handle multiple field naming conventions and improve interpretation logic for missing previous data

This commit is contained in:
DimitraVeropoulou 2026-02-16 16:05:54 +01:00
parent e16d920eea
commit e966d778f4

View file

@ -207,48 +207,57 @@ calculate_area_change_kpi <- function(current_stats, previous_stats) {
stringsAsFactors = FALSE
)
# Handle case where previous stats is NULL or empty
if (is.null(previous_stats) || nrow(previous_stats) == 0) {
result$interpretation <- "No previous data"
return(result)
}
# Match fields between current and previous stats
# Handle both naming conventions (Field_id vs field_idx)
if ("Field_id" %in% names(current_stats)) {
current_field_col <- "Field_id"
prev_field_col <- "Field_id"
ci_col <- "Mean_CI"
} else {
current_field_col <- "field_idx"
prev_field_col <- "field_idx"
ci_col <- "mean_ci"
}
# Create lookup for previous stats
prev_lookup <- setNames(
previous_stats[[ci_col]],
previous_stats[[prev_field_col]]
)
# Calculate percentage change for each field
for (i in seq_len(nrow(current_stats))) {
field_id <- current_stats$Field_id[i]
current_field_id <- current_stats[[current_field_col]][i]
current_ci <- current_stats[[ci_col]][i]
# Find matching field in previous stats
prev_idx <- which(previous_stats$Field_id == field_id)
# Find matching previous CI value
prev_ci <- prev_lookup[[as.character(current_field_id)]]
if (length(prev_idx) == 0) {
result$interpretation[i] <- "No previous data"
next
}
prev_idx <- prev_idx[1] # Take first match
current_ci <- current_stats$Mean_CI[i]
previous_ci <- previous_stats$Mean_CI[prev_idx]
if (is.na(current_ci) || is.na(previous_ci) || previous_ci == 0) {
result$interpretation[i] <- "No previous data"
next
}
# Calculate percentage change
pct_change <- ((current_ci - previous_ci) / previous_ci) * 100
result$mean_ci_pct_change[i] <- round(pct_change, 2)
# Add interpretation
if (pct_change > 15) {
result$interpretation[i] <- "Rapid growth"
} else if (pct_change > 5) {
result$interpretation[i] <- "Positive growth"
} else if (pct_change > -5) {
result$interpretation[i] <- "Stable"
} else if (pct_change > -15) {
result$interpretation[i] <- "Declining"
if (!is.null(prev_ci) && !is.na(prev_ci) && !is.na(current_ci) && prev_ci > 0) {
# Calculate percentage change
pct_change <- ((current_ci - prev_ci) / prev_ci) * 100
result$mean_ci_pct_change[i] <- round(pct_change, 2)
# Add interpretation
if (pct_change > 15) {
result$interpretation[i] <- "Rapid growth"
} else if (pct_change > 5) {
result$interpretation[i] <- "Positive growth"
} else if (pct_change > -5) {
result$interpretation[i] <- "Stable"
} else if (pct_change > -15) {
result$interpretation[i] <- "Declining"
} else {
result$interpretation[i] <- "Rapid decline"
}
} else {
result$interpretation[i] <- "Rapid decline"
result$interpretation[i] <- "No previous data"
}
}