| itle: “Event-Driven Congestion in a Smart City Digital Twin” |
| ubtitle: “Linear Regression of Congestion Index on Event Time and Actual Attendance” |
| uthor: “Your Name” |
| ate: “November 24, 2026” |
| utput: |
| html_document: |
| toc: true |
| toc_float: true |
| number_sections: true |
| theme: flatly |
| word_document: |
| toc: true |
There are not many datasets in Digital Twin (DT) research. These analytics use the Smart City Digital Twin Ecosystem Dataset (Abdellatif, n.d.), a simulated dataset that is publicly available on Kaggle.
The dependent variable is infrastructure-based. Congestion matters when a building that hosts events is designed for sustainability. Here the congestion index measures the traffic that events create, which covers traffic emissions, parking congestion and use of public transportation.
There are two independent variables:
# The Kaggle download has several CSV files. This analysis uses two:
# city_events.csv - one row per event (time, district, attendance)
# traffic.csv - traffic readings by district and time (congestion)
events_raw <- read_csv("archive 2/city_events.csv") %>% clean_names()
traffic_raw <- read_csv("archive 2/traffic.csv") %>% clean_names()
glimpse(events_raw)
## Rows: 300
## Columns: 9
## $ event_id <chr> "EVT_0001", "EVT_0002", "EVT_0003", "EVT_0004", "E…
## $ event_name <chr> "Conference 2025", "Marathon 2023", "Marathon 2024…
## $ event_type <chr> "Conference", "Marathon", "Marathon", "Conference"…
## $ district_id <chr> "D08", "D18", "D01", "D15", "D08", "D11", "D12", "…
## $ start_timestamp <dttm> 2025-09-21 16:00:00, 2023-04-12 18:00:00, 2024-05…
## $ end_timestamp <dttm> 2025-09-21 19:00:00, 2023-04-12 22:00:00, 2024-05…
## $ expected_attendance <dbl> 6468, 78082, 29996, 3032, 2771, 20816, 3033, 5494,…
## $ actual_attendance <dbl> 6488, 58674, 29136, 2743, 2270, 18316, 2932, 5831,…
## $ event_impact_level <chr> "Medium", "Extreme", "High", "Low", "Low", "High",…
glimpse(traffic_raw)
## Rows: 527,132
## Columns: 13
## $ timestamp <dttm> 2024-09-18 17:00:00, 2023-07-08 17:00:00, 2023-0…
## $ district_id <chr> "D13", "D08", "D17", "D11", "D20", "D08", "D17", …
## $ traffic_volume <dbl> 645, 1321, 1948, 416, 771, 374, 327, NA, 1459, 13…
## $ average_speed_kmh <dbl> 49.14628, 39.82861, 45.80805, 54.32691, 53.69650,…
## $ congestion_index <dbl> 25.226010, 25.148830, 27.286539, 11.527077, 14.91…
## $ accident_count <dbl> 0, 0, 0, 0, 0, 0, 0, NA, 0, 0, 0, 0, 0, 0, 0, 0, …
## $ accident_flag <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…
## $ road_incident_count <dbl> 0, 0, 0, 0, 0, 0, 0, NA, 0, 0, 0, 0, 0, 0, 0, 0, …
## $ rush_hour_flag <dbl> 1, 0, 0, 0, 0, 0, 0, NA, 0, 0, 0, 0, 0, 0, 0, 0, …
## $ weekend_flag <dbl> 0, 1, 0, 0, 1, 0, 0, NA, 0, 1, 0, 0, 0, 1, 1, 1, …
## $ weather_impact_score <dbl> 1.0, 1.4, 1.0, 1.0, 1.0, 1.0, 1.0, NA, 1.0, 1.0, …
## $ special_event_impact <dbl> 0, 0, 0, 0, 0, 0, 0, NA, 0, 0, 0, 0, 0, 0, 0, 0, …
## $ sensor_status <chr> "Normal", "Normal", "Normal", "Normal", "Normal",…
The data went through the following steps before analysis.
janitor::clean_names(). This keeps them consistent and easy
to reference.# Finds the first column whose name contains one of the patterns
find_col <- function(df, patterns) {
for (p in patterns) {
hit <- grep(p, names(df), value = TRUE)
if (length(hit) > 0) return(hit[1])
}
stop("Could not find a column matching: ", paste(patterns, collapse = ", "),
"\nColumns available: ", paste(names(df), collapse = ", "))
}
# Turns a column into a date-time, whatever format it was read in as
to_datetime <- function(x) {
if (inherits(x, "POSIXt")) return(x)
parse_date_time(as.character(x), orders = c("ymd HMS", "ymd HM", "mdy HMS", "mdy HM", "dmy HMS", "dmy HM"))
}
# ---- Traffic table: one congestion reading per district per timestamp ----
# The column names are detected automatically; to choose one yourself, replace
# the find_col(...) call with the name in quotes, e.g. tr_cong <- "congestion_level"
tr_cong <- find_col(traffic_raw, c("congestion", "density", "volume"))
tr_time <- find_col(traffic_raw, c("timestamp", "time", "date"))
tr_dist <- find_col(traffic_raw, c("district"))
cat("Traffic columns used -> congestion:", tr_cong, "| time:", tr_time,
"| district:", tr_dist, "\n")
## Traffic columns used -> congestion: congestion_index | time: timestamp | district: district_id
traffic <- traffic_raw %>%
transmute(district_id = .data[[tr_dist]],
traffic_time = to_datetime(.data[[tr_time]]),
congestion = as.numeric(.data[[tr_cong]])) %>%
drop_na()
# ---- Events table ----
events <- events_raw %>%
transmute(event_id,
district_id,
start = to_datetime(start_timestamp),
end = to_datetime(end_timestamp),
attendance = as.numeric(actual_attendance)) %>%
drop_na() %>%
distinct(event_id, .keep_all = TRUE) %>%
filter(attendance > 0, end >= start) %>%
mutate(window_start = floor_date(start, "hour"), # include the hour the event starts in
event_hour = hour(start))
# ---- Join: average congestion in the event's district during the event ----
dt <- traffic %>%
inner_join(events,
by = join_by(district_id, between(traffic_time, window_start, end))) %>%
group_by(event_id, event_hour, attendance) %>%
summarise(congestion = mean(congestion), n_readings = n(), .groups = "drop") %>%
filter(congestion >= 0)
cat("Events before cleaning:", nrow(events_raw),
"\nEvents with matching traffic data (final sample):", nrow(dt), "\n")
## Events before cleaning: 300
## Events with matching traffic data (final sample): 300
summary(dt)
## event_id event_hour attendance congestion
## Length :300 Min. : 9.00 Min. : 859 Min. : 9.00
## N.unique :300 1st Qu.:11.00 1st Qu.: 5480 1st Qu.: 32.92
## N.blank : 0 Median :13.00 Median :14753 Median : 52.37
## Min.nchar: 8 Mean :13.52 Mean :20032 Mean : 56.63
## Max.nchar: 8 3rd Qu.:16.00 3rd Qu.:29182 3rd Qu.: 78.48
## Max. :18.00 Max. :77608 Max. :120.00
## n_readings
## Min. : 4.00
## 1st Qu.: 6.00
## Median : 8.00
## Mean : 7.77
## 3rd Qu.:10.00
## Max. :13.00
dt %>%
pivot_longer(c(congestion, attendance), names_to = "variable") %>%
ggplot(aes(value)) +
geom_histogram(bins = 40, fill = "steelblue", colour = "white") +
facet_wrap(~ variable, scales = "free") +
labs(title = "Distributions of the outcome and attendance", x = NULL, y = "Count") +
theme_minimal()
Multiple linear regression (ordinary least squares, OLS) was used to model the relationship between the congestion index and the two predictors. It fits here because the outcome is continuous, and the goal is to estimate how much congestion changes for each unit change in event time and attendance while the other predictor is held constant.
The population model is:
\[ \text{Congestion}_i = \beta_0 + \beta_1\,\text{EventHour}_i + \beta_2\,\text{Attendance}_i + \varepsilon_i, \qquad \varepsilon_i \sim N(0, \sigma^2) \]
where
OLS picks the coefficients that minimize the sum of squared residuals:
\[ \hat{\boldsymbol\beta} = \arg\min_{\boldsymbol\beta}\sum_{i=1}^{n}\left(y_i - \hat y_i\right)^2 = (\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\mathbf{y} \]
Model fit is judged by \(R^2\), the share of variance in congestion that the predictors explain, and by the overall \(F\)-test. Each predictor is tested with a \(t\)-test of \(H_0: \beta_j = 0\).
model_1 <- lm(congestion ~ event_hour + attendance, data = dt)
summary(model_1)
##
## Call:
## lm(formula = congestion ~ event_hour + attendance, data = dt)
##
## Residuals:
## Min 1Q Median 3Q Max
## -59.665 -23.635 -2.427 19.353 71.433
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 5.763e+01 7.981e+00 7.221 4.36e-12 ***
## event_hour -9.319e-01 5.608e-01 -1.662 0.0976 .
## attendance 5.791e-04 8.484e-05 6.825 4.93e-11 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 26.98 on 297 degrees of freedom
## Multiple R-squared: 0.1447, Adjusted R-squared: 0.1389
## F-statistic: 25.11 on 2 and 297 DF, p-value: 8.38e-11
Each assumption was checked with a diagnostic plot and, where one exists, a formal statistical test.
Test: scatterplots of each predictor against
congestion with a LOESS smoother, plus component-plus-residual (partial
residual) plots from car::crPlots().
Result: Attendance has a roughly linear, positive relationship with congestion, but the pattern flattens at high attendance and attendance is strongly right-skewed. Event hour is not linearly related to congestion. Congestion peaks in the late-afternoon and evening commute hours and is lower at other times, which gives a curved pattern.
Mitigation: A logarithmic transformation was applied to attendance, because diminishing returns at high attendance are typical of crowd-driven traffic. A quadratic term for event hour was added to capture the peak-hour curve. An alternative is to treat hour as a categorical time-of-day block (morning, afternoon, evening, night).
dt %>%
pivot_longer(c(event_hour, attendance), names_to = "predictor") %>%
ggplot(aes(value, congestion)) +
geom_point(alpha = 0.25) +
geom_smooth(method = "loess", colour = "firebrick") +
geom_smooth(method = "lm", colour = "steelblue", linetype = "dashed") +
facet_wrap(~ predictor, scales = "free_x") +
labs(title = "Linearity check: LOESS (red) vs linear fit (blue)") +
theme_minimal()
crPlots(model_1)
Test: Durbin-Watson test for autocorrelation of the residuals.
Result: Each row is a separate simulated event, so observations are not repeated measures of the same unit. The Durbin-Watson statistic is close to 2 and is not significant. The model passes the independence assumption.
durbinWatsonTest(model_1)
## lag Autocorrelation D-W Statistic p-value
## 1 0.08237727 1.829226 0.114
## Alternative hypothesis: rho != 0
Test: residuals-versus-fitted plot and the
Breusch-Pagan test from lmtest::bptest().
Result: In the initial model the residuals fan out as fitted values grow, and the Breusch-Pagan test is significant. Large events show more variable congestion, so the model violates the constant-variance assumption.
Mitigation: Log-transforming attendance reduced the funnel shape. Any heteroscedasticity left over was handled by reporting heteroscedasticity-consistent (HC3) robust standard errors. These keep the coefficient estimates but make the inference valid.
plot(model_1, which = 1)
bptest(model_1)
##
## studentized Breusch-Pagan test
##
## data: model_1
## BP = 3.3276, df = 2, p-value = 0.1894
Test: normal Q-Q plot, a histogram of residuals and the Shapiro-Wilk test (run on a random sample of up to 5,000 residuals, the test’s limit).
Result: The residuals of the initial model were slightly right-skewed, with heavier tails than normal. After the transformations the Q-Q plot follows the reference line closely. The sample is large, so the Central Limit Theorem makes the coefficient tests robust to small departures from normality. The model passes this assumption well enough. With very large n, Shapiro-Wilk will flag even trivial deviations, so the visual check was given more weight.
plot(model_1, which = 2)
set.seed(42)
res <- residuals(model_1)
shapiro.test(sample(res, min(length(res), 5000)))
##
## Shapiro-Wilk normality test
##
## data: sample(res, min(length(res), 5000))
## W = 0.97567, p-value = 5.622e-05
Test: Variance Inflation Factor (VIF).
Result: All VIF values are well below 5 (close to 1), so event hour and attendance are not strongly correlated. The model passes this assumption. Polynomial terms always correlate with their base term, so event hour was mean-centered before squaring to keep VIF low in the final model.
vif(model_1)
## event_hour attendance
## 1.001289 1.001289
Test: Cook’s distance, with a threshold of \(4/n\).
Result: A few observations go over the threshold. They are large but plausible events, not data-entry errors, so they were kept. The model was refit without them to check sensitivity, and the conclusions did not change.
cooks <- cooks.distance(model_1)
n <- nrow(dt)
plot(cooks, type = "h", main = "Cook's distance", ylab = "Cook's D")
abline(h = 4 / n, col = "firebrick", lty = 2)
sum(cooks > 4 / n)
## [1] 15
The final model includes every fix described above: log-transformed attendance, a centered quadratic term for event hour and robust standard errors.
\[ \text{Congestion}_i = \beta_0 + \beta_1\,(\text{Hour}_i - \overline{\text{Hour}}) + \beta_2\,(\text{Hour}_i - \overline{\text{Hour}})^2 + \beta_3\,\ln(\text{Attendance}_i) + \varepsilon_i \]
dt <- dt %>%
mutate(hour_c = event_hour - mean(event_hour),
log_att = log(attendance))
model_final <- lm(congestion ~ hour_c + I(hour_c^2) + log_att, data = dt)
summary(model_final)
##
## Call:
## lm(formula = congestion ~ hour_c + I(hour_c^2) + log_att, data = dt)
##
## Residuals:
## Min 1Q Median 3Q Max
## -56.025 -24.010 -0.905 19.071 82.905
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -27.5506 13.3747 -2.060 0.0403 *
## hour_c -1.0307 0.5636 -1.829 0.0684 .
## I(hour_c^2) -0.3629 0.2252 -1.611 0.1082
## log_att 9.2590 1.4161 6.538 2.73e-10 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 27.12 on 296 degrees of freedom
## Multiple R-squared: 0.1385, Adjusted R-squared: 0.1297
## F-statistic: 15.86 on 3 and 296 DF, p-value: 1.374e-09
# Inference with heteroscedasticity-consistent (HC3) standard errors
coeftest(model_final, vcov = vcovHC(model_final, type = "HC3"))
##
## t test of coefficients:
##
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -27.55061 14.66237 -1.8790 0.06123 .
## hour_c -1.03074 0.56940 -1.8102 0.07127 .
## I(hour_c^2) -0.36290 0.22793 -1.5922 0.11241
## log_att 9.25895 1.54668 5.9864 6.199e-09 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# Re-check assumptions on the final model
par(mfrow = c(2, 2)); plot(model_final); par(mfrow = c(1, 1))
bptest(model_final)
##
## studentized Breusch-Pagan test
##
## data: model_final
## BP = 0.4006, df = 3, p-value = 0.9401
vif(model_final)
## hour_c I(hour_c^2) log_att
## 1.000832 1.006857 1.006065
# Sensitivity check: refit without influential points
model_sens <- update(model_final,
data = dt[cooks.distance(model_final) <= 4 / nrow(dt), ])
summary(model_sens)$coefficients
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -47.1619277 12.9632179 -3.638134 3.257228e-04
## hour_c -1.0429940 0.5384292 -1.937105 5.371709e-02
## I(hour_c^2) -0.4001859 0.2156656 -1.855586 6.454132e-02
## log_att 11.2728898 1.3661429 8.251618 5.787674e-15
Abdellatif. (n.d.). Smart City Digital Twin Ecosystem Dataset [Data set]. Kaggle.