This assignment uses the Smart City Digital Twin Ecosystem Dataset (Abdellatif, n.d.), a simulated dataset on Kaggle. Two of its files are used:
city_events.csv: one row per event, with its district,
start/end time and actual attendance.traffic.csv: traffic readings by district and time,
including a congestion index.Each event is matched to the traffic readings in its district while the event is running. Those readings are averaged to give one congestion value per event.
| Role | Variable | Type |
|---|---|---|
| Dependent (outcome) | congestion: average congestion index during the
event |
Continuous |
| Independent | event_hour: hour of day the event starts |
Numeric (0–23) |
| Independent | attendance: actual (not ticketed) attendance |
Continuous |
# The CSV files must be in the same folder as this .Rmd file
events_raw <- read_csv("city_events.csv") %>% clean_names()
traffic_raw <- read_csv("traffic.csv") %>% clean_names()
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"))
}
traffic <- traffic_raw %>%
transmute(district_id,
traffic_time = to_datetime(timestamp),
congestion = as.numeric(congestion_index)) %>%
drop_na()
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"),
event_hour = hour(start))
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), .groups = "drop")
nrow(dt)
## [1] 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
The model predicts congestion (a continuous outcome) from event start hour and actual attendance:
\[ \text{Congestion}_i = \beta_0 + \beta_1\,\text{EventHour}_i + \beta_2\,\text{Attendance}_i + \varepsilon_i \]
model <- lm(congestion ~ event_hour + attendance, data = dt)
summary(model)
##
## 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
The Rainbow test compares the fit of the model on the middle of the data with its fit on all of the data. If p < .05, the relationship is not linear.
dt %>%
pivot_longer(c(event_hour, attendance), names_to = "predictor") %>%
ggplot(aes(value, congestion)) +
geom_point(alpha = 0.4) +
geom_smooth(method = "lm", colour = "steelblue", se = FALSE) +
geom_smooth(method = "loess", colour = "firebrick", se = FALSE) +
facet_wrap(~ predictor, scales = "free_x") +
labs(title = "Linearity: straight-line fit (blue) vs LOESS curve (red)",
x = NULL, y = "Congestion index") +
theme_minimal()
plot(model, which = 1) # residuals vs fitted
rain <- raintest(model)
rain
##
## Rainbow test
##
## data: model
## Rain = 0.8591, df1 = 150, df2 = 147, p-value = 0.8223
A Durbin-Watson statistic near 2 means no autocorrelation. If p < .05, the errors are not independent.
dw <- dwtest(model)
dw
##
## Durbin-Watson test
##
## data: model
## DW = 1.8292, p-value = 0.06931
## alternative hypothesis: true autocorrelation is greater than 0
The points in the scale-location plot should form an even, flat band. If the Breusch-Pagan test gives p < .05, the variance is not constant.
plot(model, which = 3) # scale-location
bp <- bptest(model)
bp
##
## studentized Breusch-Pagan test
##
## data: model
## BP = 3.3276, df = 2, p-value = 0.1894
On the Q-Q plot, the points should follow the line. If the Shapiro-Wilk test gives p < .05, the residuals are not normally distributed.
plot(model, which = 2) # normal Q-Q
hist(residuals(model), breaks = 30, col = "steelblue", border = "white",
main = "Histogram of residuals", xlab = "Residual")
sw <- shapiro.test(residuals(model))
sw
##
## Shapiro-Wilk normality test
##
## data: residuals(model)
## W = 0.97567, p-value = 5.622e-05
VIF values below 5 and a correlation between the predictors below about |0.7| mean multicollinearity is not a problem.
vifs <- vif(model)
vifs
## event_hour attendance
## 1.001289 1.001289
cors <- cor(dt %>% select(event_hour, attendance, congestion))
round(cors, 3)
## event_hour attendance congestion
## event_hour 1.000 -0.036 -0.102
## attendance -0.036 1.000 0.370
## congestion -0.102 0.370 1.000
The model meets most of the assumptions:
The main violation is normality of residuals.
With 300 events, the Central Limit Theorem means the coefficient tests are fairly robust to non-normal residuals. However, the violation should still be addressed and checked.
Three steps were taken:
hist(dt$attendance, breaks = 30, col = "grey70", border = "white",
main = "Attendance (raw): right-skewed", xlab = "Actual attendance")
hist(log(dt$attendance), breaks = 30, col = "steelblue", border = "white",
main = "log(Attendance): more symmetric", xlab = "log(actual attendance)")
model_log <- lm(congestion ~ event_hour + log(attendance), data = dt)
sw_log <- shapiro.test(residuals(model_log))
sw_log
##
## Shapiro-Wilk normality test
##
## data: residuals(model_log)
## W = 0.9771, p-value = 9.969e-05
Box-Cox finds the power λ that makes the residuals closest to normal. For example, λ = 1 means no change, λ = 0.5 is a square root and λ = 0 is a log.
bc <- boxcox(congestion ~ event_hour + log(attendance), data = dt, lambda = seq(-1, 2, 0.05))
lambda <- bc$x[which.max(bc$y)]
lambda
## [1] 0.4848485
# Round to a transformation that is easy to explain
lam_r <- if (abs(lambda) < 0.25) 0 else if (abs(lambda - 0.5) < 0.25) 0.5 else round(lambda, 1)
dt <- dt %>%
mutate(congestion_t = if (lam_r == 0) log(congestion)
else if (lam_r == 0.5) sqrt(congestion)
else (congestion^lam_r - 1) / lam_r)
model_fixed <- lm(congestion_t ~ event_hour + log(attendance), data = dt)
summary(model_fixed)
##
## Call:
## lm(formula = congestion_t ~ event_hour + log(attendance), data = dt)
##
## Residuals:
## Min 1Q Median 3Q Max
## -4.3878 -1.5260 0.0566 1.3139 5.2586
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2.56697 1.06269 2.416 0.0163 *
## event_hour -0.08446 0.03888 -2.172 0.0306 *
## log(attendance) 0.62051 0.09745 6.368 7.27e-10 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.872 on 297 degrees of freedom
## Multiple R-squared: 0.1325, Adjusted R-squared: 0.1267
## F-statistic: 22.68 on 2 and 297 DF, p-value: 6.81e-10
par(mfrow = c(1, 2))
qqnorm(residuals(model), main = "Before: original model"); qqline(residuals(model), col = "red")
qqnorm(residuals(model_fixed), main = "After: transformed model"); qqline(residuals(model_fixed), col = "red")
par(mfrow = c(1, 1))
sw_fixed <- shapiro.test(residuals(model_fixed))
sw_fixed
##
## Shapiro-Wilk normality test
##
## data: residuals(model_fixed)
## W = 0.98701, p-value = 0.008457
# Re-check the other assumptions on the new model
raintest(model_fixed)
##
## Rainbow test
##
## data: model_fixed
## Rain = 0.86246, df1 = 150, df2 = 147, p-value = 0.816
dwtest(model_fixed)
##
## Durbin-Watson test
##
## data: model_fixed
## DW = 1.8483, p-value = 0.09432
## alternative hypothesis: true autocorrelation is greater than 0
bptest(model_fixed)
##
## studentized Breusch-Pagan test
##
## data: model_fixed
## BP = 3.2738, df = 2, p-value = 0.1946
vif(model_fixed)
## event_hour log(attendance)
## 1.000012 1.000012
| Model | Shapiro-Wilk W | Shapiro-Wilk p | R-squared |
|---|---|---|---|
| Original | 0.9757 | 0.0001 | 0.1447 |
| log(attendance) | 0.9771 | 0.0001 | 0.1309 |
| log(attendance) + Box-Cox outcome | 0.9870 | 0.0085 | 0.1325 |
The bootstrap resamples the 300 events with replacement 2,000 times and refits the model each time. The confidence intervals come from the actual spread of the estimates, so they do not assume the residuals are normal.
set.seed(123)
boot_coefs <- replicate(2000, {
idx <- sample(nrow(dt), replace = TRUE)
coef(lm(congestion ~ event_hour + log(attendance), data = dt[idx, ]))
})
boot_ci <- t(apply(boot_coefs, 1, quantile, probs = c(.025, .975)))
cbind(Estimate = coef(model_log), boot_ci) %>% round(4)
## Estimate 2.5% 97.5%
## (Intercept) -14.4071 -45.8153 17.1975
## event_hour -1.0567 -2.1413 0.0170
## log(attendance) 9.0820 5.9527 12.1207
The Box-Cox analysis suggested λ ≈ 0.48, so congestion was square-root transformed. After the fixes, the Shapiro-Wilk p-value changed from < .001 to = 0.008. The residuals are closer to normal but still do not fully pass the test. This is common with a bounded index like congestion. Because the sample is large and the bootstrapped confidence intervals lead to the same conclusions as the regular model, the non-normality does not change the results.
Across all versions of the model, the conclusion stays the same. Actual attendance is a significant positive predictor of congestion (its bootstrapped 95% CI, 5.95 to 12.12, does not include zero), while event start time is not (its 95% CI, -2.14 to 0.02, includes zero).
Abdellatif. (n.d.). Smart City Digital Twin Ecosystem Dataset [Data set]. Kaggle.