WQD7004 Programming for Data Science - Group Project (Group 8)
Retail food prices are one of the most visible economic signals for
Malaysian households, yet public discussion usually rests on a single
national average. The PriceCatcher dataset published by
the Ministry of Domestic Trade and Cost of Living (KPDN) through
data.gov.my offers something far richer: item level price
observations collected at named retail premises across every state,
month after month.
This report uses three consecutive years of PriceCatcher data (January 2024 to November 2026, 35 monthly files) to answer two questions with statistical models rather than anecdotes.
Research Question 1 (regression). After controlling for what is being sold and when it is sold, how much do location (state), outlet type (hypermarket, supermarket, mini market, wet market, small shop) and item category shift the price level of a recorded basket, and has that level risen or fallen between 2024 and 2026?
Research Question 2 (classification). Can the price profile, location and item mix of an outlet predict whether it is a modern outlet (hypermarket, supermarket or mini market) or a traditional one (wet market or small provision shop)? In other words, is the modern-versus-traditional price gap strong enough to be learned from data?
The analysis follows the three stages required by the project brief: exploration of structure and data quality, cleaning with base R, and analysis using one regression and one classification model. Every figure in this document is produced by the R code shown immediately above it, so the whole report can be reproduced by knitting this file.
PriceCatcher is published by the Ministry of Domestic Trade and Cost of Living (KPDN) for price surveillance: it tracks the retail prices of a fixed panel of everyday items at a panel of premises so that price movements and the geographic spread can be monitored. It is a monitoring instrument rather than a census of all retail transactions, which sets the interpretation limits used throughout this report.
It is distributed as one CSV per month plus two lookup tables. The master file has only four columns, which makes the dataset easy to join but forces us to attach meaning through the lookups:
date - observation datepremise_code - identifier of the shop or market
stallitem_code - identifier of the productprice - price in Malaysian Ringgit (RM)The lookup tables add the descriptive variables used later:
lookup_item.csv (797 items, with item,
item_group, item_category, unit)
and lookup_premise.csv (3,932 premises, with
premise, premise_type, state,
district).
items <- read.csv(file.path(data_dir, "lookup_item.csv"), stringsAsFactors = FALSE)
premises <- read.csv(file.path(data_dir, "lookup_premise.csv"), stringsAsFactors = FALSE)
cat("lookup_item:", nrow(items), "rows x", ncol(items), "columns\n")## lookup_item: 797 rows x 5 columns
cat("lookup_premise:", nrow(premises), "rows x", ncol(premises), "columns\n")## lookup_premise: 3932 rows x 6 columns
str(items)## 'data.frame': 797 obs. of 5 variables:
## $ item_code : int -1 1 2 3 9 10 11 12 14 16 ...
## $ item : chr "" "AYAM BERSIH - STANDARD" "AYAM BERSIH - SUPER" "AYAM HIDUP" ...
## $ unit : chr "" "1kg" "1kg" "1kg" ...
## $ item_group : chr "" "BARANGAN SEGAR" "BARANGAN SEGAR" "BARANGAN SEGAR" ...
## $ item_category: chr "" "AYAM" "AYAM" "AYAM" ...
str(premises)## 'data.frame': 3932 obs. of 6 variables:
## $ premise_code: int -1 2 3 6 7 8 15 16 115 136 ...
## $ premise : chr "Unknown Premise" "PASAR BESAR IPOH" "JUSCO AYER KEROH" "KEDAI RUNCIT TAFAZ MAJU PRESINT 9" ...
## $ address : chr "Unknown Address" "JALAN LAKSAMANA,TAMAN JUBILEE,30300 IPOH, PERAK" "LOT 4991,MUKIM BUKIT BARU,75450 LEBUH AYER KEROH, MELAKA" "NO.5, JALAN P9B/1,PRESINT 9,62250 PUTRAJAYA" ...
## $ premise_type: chr "" "Pasar Basah " "Pasar Raya / Supermarket" "Kedai Runcit" ...
## $ state : chr "" "Perak" "Melaka" "W.P. Putrajaya" ...
## $ district : chr "" "Kinta" "Melaka Tengah" "Wp Putrajaya" ...
# Run once if the files are not already in ./data.
# The official endpoint is public and stable.
base_url <- "https://storage.data.gov.my/pricecatcher/%s.csv"
# the two lookup tables
for (lk in c("lookup_item", "lookup_premise")) {
f <- file.path(data_dir, paste0(lk, ".csv"))
if (!file.exists(f)) download.file(sprintf(base_url, lk), f, mode = "wb")
}
# the monthly files, 2024-01 to 2026-11
for (y in 2024:2026) {
last <- if (y == 2026) 11 else 12 # 2026 is published only up to November
for (m in 1:last) {
f <- file.path(data_dir, sprintf("pricecatcher_%d-%02d.csv", y, m))
if (!file.exists(f)) {
download.file(sprintf(base_url, sprintf("pricecatcher_%d-%02d", y, m)), f, mode = "wb")
}
}
}Thirty-five monthly files hold roughly 74 million rows, far more than a student laptop should hold in memory at once. The reading step therefore streams: each monthly file is read, joined to the lookups, summarised, and reduced to a 5% random sample before the next file is opened. Monthly medians are computed from every record on the way, and the figures below are checked against them: sampling alone moves a monthly median by at most RM 0.09, and the full pipeline (sampling plus the outlier filter) by at most RM 0.35.
years <- 2024:2026
last_month <- c("2024" = 12, "2025" = 12, "2026" = 11)
item_group_map <- trimws(items$item_group)
premise_type_map <- trimws(premises$premise_type)
state_map <- trimws(premises$state)
records <- list() # one row per month: row counts and medians
sample_list <- list() # 5% sample used for modelling
for (y in years) {
yy <- as.character(y)
for (m in 1:last_month[yy]) {
f <- file.path(data_dir, sprintf("pricecatcher_%s-%02d.csv", yy, m))
d <- read.csv(f, stringsAsFactors = FALSE,
colClasses = c(date = "character", premise_code = "integer",
item_code = "integer", price = "numeric"))
ig <- item_group_map[match(d$item_code, items$item_code)]
pt <- premise_type_map[match(d$premise_code, premises$premise_code)]
st <- state_map[match(d$premise_code, premises$premise_code)]
keep <- !is.na(ig) & ig != "" & !is.na(pt) & pt != "" & !is.na(st) & st != ""
raw_n <- nrow(d)
d <- d[keep, ]
ig <- ig[keep]; pt <- pt[keep]; st <- st[keep]
records[[paste0(yy, sprintf("%02d", m))]] <- data.frame(
year = yy, month = sprintf("%02d", m), raw = raw_n, clean = nrow(d),
median_all = median(d$price),
chicken_median = median(d$price[d$item_code == 1]),
stringsAsFactors = FALSE)
idx <- sample.int(nrow(d), round(nrow(d) * 0.05))
sample_list[[paste0(yy, sprintf("%02d", m))]] <- data.frame(
price = d$price[idx], item_code = d$item_code[idx],
item_group = ig[idx], premise_type = pt[idx], state = st[idx],
year = yy, month = sprintf("%02d", m), stringsAsFactors = FALSE)
rm(d, ig, pt, st, keep); invisible(gc(FALSE))
}
}
rec <- do.call(rbind, records); rownames(rec) <- NULL
bc <- do.call(rbind, sample_list); rownames(bc) <- NULL
rm(records, sample_list); invisible(gc())
cat("monthly files processed:", nrow(rec), "\n")## monthly files processed: 35
cat("total raw rows:", format(sum(rec$raw), big.mark = ","), "\n")## total raw rows: 74,084,095
cat("total rows after lookup filter:", format(sum(rec$clean), big.mark = ","), "\n")## total rows after lookup filter: 72,644,627
cat("modelling sample:", format(nrow(bc), big.mark = ","), "rows\n")## modelling sample: 3,632,232 rows
dim_tab <- data.frame(
Dataset = c("PriceCatcher master, one month", "PriceCatcher, 35 months combined",
"Modelling sample after both lookups (5% per month)",
"lookup_item", "lookup_premise"),
Rows = c(format(as.integer(round(mean(rec$raw))), big.mark = ","),
format(as.integer(sum(rec$raw)), big.mark = ","),
format(nrow(bc), big.mark = ","),
format(nrow(items), big.mark = ","),
format(nrow(premises), big.mark = ",")),
Columns = c(4, 4, 7, ncol(items), ncol(premises)))
knitr::kable(dim_tab, caption = paste0(
"Dimensions of the data used in this report. The master file has four columns (date, ",
"premise_code, item_code, price); the lookups add item category and premise type/state, ",
"so the modelling table carries seven variables and reuses premise and item codes ",
"only as join keys."))| Dataset | Rows | Columns |
|---|---|---|
| PriceCatcher master, one month | 2,116,688 | 4 |
| PriceCatcher, 35 months combined | 74,084,095 | 4 |
| Modelling sample after both lookups (5% per month) | 3,632,232 | 7 |
| lookup_item | 797 | 5 |
| lookup_premise | 3,932 | 6 |
The master’s four columns and the analysis table’s seven variables are different things, and both dimensions matter: 74,084,095 records arrive in four columns, and the analysis table is wider than the source but far shorter, at 3,632,232 rows. ## Data quality checks
The checks below were run on the complete 35-month read. The 2026-09 file is used as the concrete example because it is representative of the structure.
one <- read.csv(file.path(data_dir, "pricecatcher_2026-09.csv"), stringsAsFactors = FALSE,
colClasses = c(date = "character", premise_code = "integer",
item_code = "integer", price = "numeric"))
key <- paste(one$date, one$premise_code, one$item_code)
qual <- data.frame(
Check = c("Rows in one monthly file (2026-09)", "Distinct dates in that file",
"Distinct premises", "Distinct items", "Missing price values",
"Prices equal to zero", "Duplicate (date, premise, item) keys",
"Rows whose item code is absent from lookup_item",
"Rows whose premise code is absent from lookup_premise",
"Share of rows dropped by the lookup filter, 35 months"),
Result = c(format(nrow(one), big.mark = ","),
as.character(length(unique(one$date))),
format(length(unique(one$premise_code)), big.mark = ","),
as.character(length(unique(one$item_code))),
as.character(sum(is.na(one$price))),
as.character(sum(one$price == 0, na.rm = TRUE)),
as.character(sum(duplicated(key))),
format(sum(is.na(match(one$item_code, items$item_code))), big.mark = ","),
as.character(sum(is.na(match(one$premise_code, premises$premise_code)))),
paste0(round(100 * (sum(rec$raw) - sum(rec$clean)) / sum(rec$raw), 2), "%")))
knitr::kable(qual, caption = "Data quality summary")| Check | Result |
|---|---|
| Rows in one monthly file (2026-09) | 1,742,320 |
| Distinct dates in that file | 28 |
| Distinct premises | 2,142 |
| Distinct items | 343 |
| Missing price values | 0 |
| Prices equal to zero | 0 |
| Duplicate (date, premise, item) keys | 0 |
| Rows whose item code is absent from lookup_item | 26,191 |
| Rows whose premise code is absent from lookup_premise | 0 |
| Share of rows dropped by the lookup filter, 35 months | 1.94% |
Three findings shape the cleaning strategy:
lookup_premise in
every month except one: 273 rows in February 2024 carry premise code
20927, which is absent from the lookup (0.0004% of all
rows). Item codes are the larger gap: 1,439,198 rows (1.94%) have an
item code that is not in lookup_item, between 0.97% and
2.56% in a single month. Three rows fail both lookups, so the filter
drops 1,439,468 rows (1.94%) and keeps 72,644,627.
Those rows carry no item category (and, for the 273, no outlet type or
state either), so they cannot enter an analysis that groups by category
or channel.hist(one$price[one$price < 200], breaks = 200, col = "#9ecae1", border = "white",
main = "Price distribution, September 2026 (prices below RM 200)",
xlab = "Price (RM)", ylab = "Number of records")Distribution of recorded prices in 2026-09. Most observations sit between RM 1 and RM 30; a small tail above RM 500 is unit confusion or bulk packaging rather than a true retail price.
Cleaning was done in base R, without any add-on package, in four explicit steps. Each step is reported with its row count so that the effect of every decision is visible.
match() attaches item_group,
premise_type and state. Two repairs happen
here. First, every text label is passed through trimws(),
because lookup_premise contains both
"Pasar Basah" and "Pasar Basah " (trailing
space) as separate strings, and an untrimmed join would silently split
one channel into two factor levels. Second, rows that receive an empty
value are dropped, because a price without a category cannot be
interpreted. In practice the drop is entirely composed of item codes
that are absent from lookup_item: 1.94% of the raw rows
across the three years, and no row is lost because of the premise or
state mapping.
Prices of zero or below would break the logarithmic transformation used in the regression. The quality check shows there are none, but the rule stays in the code so that future monthly files are protected.
The largest source of distortion is unit confusion: the same item code is sometimes recorded per kilogram and sometimes per pack, producing prices that are ten or a hundred times too high. Filtering globally by item would delete genuine regional differences, because a chicken really does cost RM 12.90 in Sabah and RM 8.40 in Johor. The filter is therefore applied within each item, separately in each state:
item_code, state) pair;[Q1 - 1.5 x IQR, Q3 + 1.5 x IQR];A 5% random sample of every month is drawn with a fixed seed, so that the regression and the classification model run on a normal laptop. The descriptive tables and figures in this report are computed on that sample, and the sample is checked against the full-data monthly medians kept during the streaming read in two separate steps, because the comparison has to hold the cleaning constant:
So sampling changes the level by less than a sen on average, while the interquartile filter is the larger of the two effects and is the one worth quoting when a number in a figure is questioned.
grp <- interaction(bc$item_code, bc$state, drop = TRUE)
q1 <- ave(bc$price, grp, FUN = function(p) quantile(p, 0.25, na.rm = TRUE))
q3 <- ave(bc$price, grp, FUN = function(p) quantile(p, 0.75, na.rm = TRUE))
iqr <- q3 - q1
outlier <- bc$price < (q1 - 1.5 * iqr) | bc$price > (q3 + 1.5 * iqr)
clean <- bc[!outlier, ]
rm(grp, q1, q3, iqr, outlier); invisible(gc())
clean_tab <- data.frame(
Stage = c("Raw rows, 35 files", "After lookup filter", "Modelling sample (5%)",
"After item x state IQR filter"),
Rows = c(format(sum(rec$raw), big.mark = ","),
format(sum(rec$clean), big.mark = ","),
format(nrow(bc), big.mark = ","),
format(nrow(clean), big.mark = ",")),
Share_of_raw = c("100.00%",
paste0(round(100 * sum(rec$clean) / sum(rec$raw), 2), "%"),
paste0(round(100 * nrow(bc) / sum(rec$raw), 2), "%"),
paste0(round(100 * nrow(clean) / sum(rec$raw), 2), "%")))
knitr::kable(clean_tab, caption = "Row counts at each cleaning stage")| Stage | Rows | Share_of_raw |
|---|---|---|
| Raw rows, 35 files | 74,084,095 | 100.00% |
| After lookup filter | 72,644,627 | 98.06% |
| Modelling sample (5%) | 3,632,232 | 4.9% |
| After item x state IQR filter | 3,528,796 | 4.76% |
par(mfrow = c(1, 2), mar = c(4, 4, 3, 1))
boxplot(bc$price[bc$item_group == "BARANGAN SEGAR"], ylim = c(0, 120),
col = "#f4a582", main = "Before filtering", ylab = "Price (RM)")
boxplot(clean$price[clean$item_group == "BARANGAN SEGAR"], ylim = c(0, 120),
col = "#9ecae1", main = "After filtering", ylab = "Price (RM)")Before and after the item-by-state interquartile filter for the fresh-food category. Outliers are drawn: 0.33% of fresh-food records exceed RM 60 and 9 records exceed RM 300, so the axis is cut at RM 120 to keep the box readable. The filter removes that tail while the median and the box stay where they were.
The dependent variable is log(price). A logarithmic
scale is used because retail prices are multiplicative: a RM 2 item and
a RM 30 item should not carry the same absolute error. Coefficients can
then be read as approximate percentage differences through
100 x (exp(beta) - 1).
The explanatory variables are:
state (16 levels) - regional price level, baseline
Johor;premise_type (6 levels) - outlet channel, baseline
deliberately set to Hypermarket, the largest and most
standardised channel;item_group (6 levels) - product category, baseline
BARANGAN BERBUNGKUS (packaged goods);month (12 levels) - seasonality, baseline January;year (3 levels) - the annual level shift, baseline
2024.Setting the baseline explicitly matters. If R picks the
alphabetically first level, Borong (wholesale, a few
hundred records) becomes the reference and every coefficient is measured
against a channel that represents 0.02% of the data.
relevel() is therefore applied before estimation.
md <- clean
md$premise_type <- relevel(factor(md$premise_type), ref = "Hypermarket")
md$year <- factor(md$year, levels = c("2024", "2025", "2026"))
md$month <- factor(md$month, levels = sprintf("%02d", 1:12))
md$log_price <- log(md$price)
set.seed(25125517)
fit_dat <- md[sample.int(nrow(md), 1000000), ]
cat("regression rows:", format(nrow(fit_dat), big.mark = ","), "\n")## regression rows: 1,000,000
fit_a <- lm(log_price ~ item_group + state + premise_type + month + year, data = fit_dat)
sum_a <- summary(fit_a)
cat("Adjusted R-squared:", round(sum_a$adj.r.squared, 4), "\n")## Adjusted R-squared: 0.0924
cat("F statistic p-value:",
format.pval(pf(sum_a$fstatistic[1], sum_a$fstatistic[2], sum_a$fstatistic[3],
lower.tail = FALSE), digits = 3), "\n")## F statistic p-value: <2e-16
The adjusted R-squared of 0.0924 looks modest, and that is expected. Most of the variation in a grocery price is which item it is: a bottle of cooking oil and a packet of instant noodles differ by a factor of ten before any regional or channel effect is considered. Because the model deliberately leaves out item identity (797 items are too many to enter as a categorical variable in a teaching model), the remaining systematic effects - state, channel, category, season, year - can only explain about 9% of the variance. With one million observations every effect below is estimated with a very narrow confidence interval, so the low R-squared is not a problem of sample size.
co_a <- summary(fit_a)$coefficients
st_rows <- grep("^state", rownames(co_a))
knitr::kable(data.frame(
State = sub("^state", "", rownames(co_a)[st_rows]),
Effect_on_log_price = round(co_a[st_rows, 1], 4),
Approx_percent = round(100 * (exp(co_a[st_rows, 1]) - 1), 1),
Std_error = round(co_a[st_rows, 2], 4),
p_value = format.pval(co_a[st_rows, 4], digits = 3)),
caption = "State effects on log price, baseline Johor")| State | Effect_on_log_price | Approx_percent | Std_error | p_value | |
|---|---|---|---|---|---|
| stateKedah | Kedah | -0.0442 | -4.3 | 0.0040 | < 2e-16 |
| stateKelantan | Kelantan | -0.0358 | -3.5 | 0.0037 | < 2e-16 |
| stateMelaka | Melaka | 0.0210 | 2.1 | 0.0057 | 0.000222 |
| stateNegeri Sembilan | Negeri Sembilan | -0.0154 | -1.5 | 0.0048 | 0.001227 |
| statePahang | Pahang | -0.0046 | -0.5 | 0.0035 | 0.190149 |
| statePerak | Perak | -0.0054 | -0.5 | 0.0034 | 0.111230 |
| statePerlis | Perlis | -0.0662 | -6.4 | 0.0068 | < 2e-16 |
| statePulau Pinang | Pulau Pinang | 0.0187 | 1.9 | 0.0037 | 5.07e-07 |
| stateSabah | Sabah | 0.0948 | 9.9 | 0.0039 | < 2e-16 |
| stateSarawak | Sarawak | 0.1109 | 11.7 | 0.0035 | < 2e-16 |
| stateSelangor | Selangor | 0.0571 | 5.9 | 0.0036 | < 2e-16 |
| stateTerengganu | Terengganu | -0.0471 | -4.6 | 0.0041 | < 2e-16 |
| stateW.P. Kuala Lumpur | W.P. Kuala Lumpur | 0.1267 | 13.5 | 0.0033 | < 2e-16 |
| stateW.P. Labuan | W.P. Labuan | 0.1431 | 15.4 | 0.0102 | < 2e-16 |
| stateW.P. Putrajaya | W.P. Putrajaya | 0.1081 | 11.4 | 0.0071 | < 2e-16 |
stv <- co_a[st_rows, 1]; names(stv) <- sub("^state", "", rownames(co_a)[st_rows])
stv <- sort(stv)
par(mar = c(4.5, 12, 3, 1.5), las = 1)
dotchart(stv, pch = 19, col = "#08519c",
xlab = "Log price difference vs Johor",
main = "State price effect, 2024-2026 model")
abline(v = 0, lty = 2, col = "grey60")State price effects estimated by the regression. Johor is the baseline at zero. The five highest bars are East Malaysia or a Federal Territory, which confirms that geography is priced in.
Two patterns stand out:
pt_rows <- grep("^premise_type", rownames(co_a))
knitr::kable(data.frame(
Outlet_type = sub("^premise_type", "", rownames(co_a)[pt_rows]),
Effect_on_log_price = round(co_a[pt_rows, 1], 4),
Approx_percent = round(100 * (exp(co_a[pt_rows, 1]) - 1), 1),
p_value = format.pval(co_a[pt_rows, 4], digits = 3)),
caption = "Outlet type effects, baseline Hypermarket")| Outlet_type | Effect_on_log_price | Approx_percent | p_value | |
|---|---|---|---|---|
| premise_typeBorong | Borong | 0.0003 | 0.0 | 0.995 |
| premise_typeKedai Runcit | Kedai Runcit | -0.1082 | -10.3 | < 2e-16 |
| premise_typePasar Basah | Pasar Basah | 0.0763 | 7.9 | < 2e-16 |
| premise_typePasar Mini | Pasar Mini | -0.0299 | -2.9 | < 2e-16 |
| premise_typePasar Raya / Supermarket | Pasar Raya / Supermarket | -0.0118 | -1.2 | 1.67e-06 |
The channel ranking is the headline result of this model:
Pasar Basah records +7.9% above a
hypermarket for the observed basket, and the effect is highly
significant. This contradicts the common assumption that traditional
markets are cheaper; in this data they are not, once category and state
are held constant.Kedai Runcit records -10.3%. They sell a
narrow range of low-priced staples, so their recorded basket is
cheap.yt <- aggregate(price ~ year + premise_type, data = clean, FUN = median)
pt_keep <- c("Hypermarket", "Pasar Raya / Supermarket", "Pasar Mini",
"Kedai Runcit", "Pasar Basah")
m2 <- sapply(c("2024", "2025", "2026"), function(y)
yt$price[yt$year == y][match(pt_keep, yt$premise_type[yt$year == y])])
tab_pt <- data.frame(Outlet = pt_keep, RM_2024 = m2[, 1], RM_2025 = m2[, 2],
RM_2026 = m2[, 3], Change = m2[, 3] - m2[, 1])
knitr::kable(tab_pt, digits = 2,
caption = "Median recorded price by outlet type, 5% sample")| Outlet | RM_2024 | RM_2025 | RM_2026 | Change |
|---|---|---|---|---|
| Hypermarket | 8.99 | 8.9 | 8.50 | -0.49 |
| Pasar Raya / Supermarket | 8.99 | 8.9 | 8.90 | -0.09 |
| Pasar Mini | 7.20 | 8.0 | 9.65 | 2.45 |
| Kedai Runcit | 6.50 | 7.0 | 8.50 | 2.00 |
| Pasar Basah | 10.00 | 10.0 | 10.00 | 0.00 |
lab <- c("Hypermarket", "Supermarket", "Mini market", "Kedai Runcit", "Pasar Basah")
par(mar = c(8, 4.5, 3, 1.5))
barplot(t(m2), beside = TRUE, names.arg = lab, las = 2, cex.names = 0.78,
col = c("#9ecae1", "#4292c6", "#08519c"), ylim = c(0, 11.7),
ylab = "Median price (RM)", main = "Median price by outlet type, 2024-2026")
legend("topleft", legend = c("2024", "2025", "2026"),
fill = c("#9ecae1", "#4292c6", "#08519c"), bty = "n", cex = 0.8)Median recorded price by outlet type. Wet markets sit flat at RM 10.00 in all three years, hypermarkets drift down from RM 8.99 to RM 8.50, while mini markets (RM 7.20 to 9.65) and provision shops (RM 6.50 to 8.50) climb to hypermarket level.
Axis labels in this figure use the short English names:
Supermarket stands for
Pasar Raya / Supermarket and Mini market for
Pasar Mini; the table above keeps the official labels.
The chart is the single most useful sanity check in this report, because it contradicts the regression at first sight. A provision shop and a hypermarket now share exactly the same median (RM 8.50 against RM 8.50), yet the regression says provision shops are 10.3% cheaper. Both statements are correct. The shop sells a cheaper mix of products and sits in cheaper states, so its raw median comes out low; hold category, state, month and year constant and the same-item price in the shop is higher. Two further readings follow from the table: the raw gap between small shops and hypermarkets closed within three years (provision shops +RM 2.00, mini markets +RM 2.45, hypermarkets -RM 0.49), and wet markets never moved from RM 10.00, so they were the dearest channel in 2024 and the dearest by a wider margin in 2026. This is why the item-normalised model in Section 4.6 exists, and why the two models must be read together rather than in isolation.
Wholesale (Borong) is deliberately absent from the
chart. It carries only 749 records in the 5% sample (0.02%), so a median
for it would be a statement about a handful of premises, not about a
channel.
gr_rows <- grep("^item_group", rownames(co_a))
mo_rows <- grep("^month", rownames(co_a))
yr_rows <- grep("^year", rownames(co_a))
knitr::kable(rbind(
data.frame(Term = sub("^item_group", "", rownames(co_a)[gr_rows]),
Approx_percent = round(100 * (exp(co_a[gr_rows, 1]) - 1), 1)),
data.frame(Term = paste("Month", sub("^month", "", rownames(co_a)[mo_rows]),
"(vs January)"),
Approx_percent = round(100 * (exp(co_a[mo_rows, 1]) - 1), 1)),
data.frame(Term = paste("Year", sub("^year", "", rownames(co_a)[yr_rows]),
"(vs 2024)"),
Approx_percent = round(100 * (exp(co_a[yr_rows, 1]) - 1), 1))),
caption = "Category, seasonal and annual effects as approximate percentage change")| Term | Approx_percent | |
|---|---|---|
| item_groupBARANGAN KERING | BARANGAN KERING | -12.7 |
| item_groupBARANGAN SEGAR | BARANGAN SEGAR | 16.8 |
| item_groupMINUMAN | MINUMAN | -28.7 |
| item_groupPRODUK KEBERSIHAN | PRODUK KEBERSIHAN | 31.7 |
| item_groupSUSU DAN BARANGAN BAYI | SUSU DAN BARANGAN BAYI | 255.4 |
| month02 | Month 02 (vs January) | -4.7 |
| month03 | Month 03 (vs January) | -5.4 |
| month04 | Month 04 (vs January) | -6.2 |
| month05 | Month 05 (vs January) | -5.2 |
| month06 | Month 06 (vs January) | -3.4 |
| month07 | Month 07 (vs January) | -4.8 |
| month08 | Month 08 (vs January) | -5.2 |
| month09 | Month 09 (vs January) | -5.8 |
| month10 | Month 10 (vs January) | -4.8 |
| month11 | Month 11 (vs January) | -4.1 |
| month12 | Month 12 (vs January) | -1.1 |
| year2025 | Year 2025 (vs 2024) | -4.3 |
| year2026 | Year 2026 (vs 2024) | -5.2 |
SUSU DAN BARANGAN BAYI) are the most expensive category,
about 3.6 times the packaged-goods baseline; cleaning
products (+31.7%) and fresh food (+16.8%) follow. Beverages (-28.7%) and
dry goods (-12.7%) are the cheapest.mon <- aggregate(price ~ year + month, data = clean, FUN = median)
mon <- mon[order(mon$year, mon$month), ]
par(mar = c(5.5, 4.5, 3, 1.5))
plot(seq_len(nrow(mon)), mon$price, type = "o", pch = 19, cex = 0.55, col = "#08519c",
xaxt = "n", xlab = "", ylab = "Median price (RM)",
main = "Monthly median price, January 2024 - November 2026")
axis(1, at = seq_len(nrow(mon)), labels = FALSE, tcl = -0.3)
jan <- which(mon$month == "01")
abline(v = jan, lty = 3, col = "grey70")
mtext(paste("Jan", mon$year[jan]), side = 1, at = jan, line = 0.9, cex = 0.8)Monthly median price across the 35 monthly files, computed on the 5% sample after the interquartile filter. Sampling alone moves a monthly median by at most RM 0.09, and the full pipeline by at most RM 0.35 (January 2024, drawn at 9.50 against 9.85 on the full data). A trough in the second quarter and a peak in December repeat in both complete years, but the annual level itself is flat (RM 9.00, 8.90, 9.00), so the month-to-month movement is a seasonal and composition effect rather than a trend.
The annual coefficient above compares observations that happen to be recorded in each year, and item coverage is shrinking (483 items in 2024, 502 in 2025, only 324 in 2026). A composition effect therefore contaminates any raw year-on-year comparison: the 2026 basket may simply contain cheaper products.
The fix is to compare the same item codes. Only the 302 items observed in all three years are kept, and the comparison is restricted to January-November so that the missing December 2026 does not bias it (December is the most expensive month of the year: RM 9.50 in 2024 and RM 9.90 in 2025, against RM 9.00 in November in both years). Note what this does and does not fix: it pins the set of product codes, but each product, state and outlet type still enters in whatever proportion it happened to be recorded that year. The medians below are therefore pooled-basket medians, not a fixed-weight price index.
a24 <- unique(clean$item_code[clean$year == "2024"])
a25 <- unique(clean$item_code[clean$year == "2025"])
a26 <- unique(clean$item_code[clean$year == "2026"])
basket <- Reduce(intersect, list(a24, a25, a26))
jn <- clean[clean$month %in% sprintf("%02d", 1:11), ]
bs <- jn[jn$item_code %in% basket, ]
basket_tab <- data.frame(
Year = c("2024", "2025", "2026"),
Items_available = c(length(a24), length(a25), length(a26)),
Median_all_items = as.numeric(tapply(jn$price, jn$year, median)),
Median_constant_basket = as.numeric(tapply(bs$price, bs$year, median)),
Median_chicken = as.numeric(tapply(jn$price[jn$item_code == 1],
jn$year[jn$item_code == 1], median)))
knitr::kable(basket_tab,
caption = "January-November comparison: all items versus the same 302-item basket")| Year | Items_available | Median_all_items | Median_constant_basket | Median_chicken |
|---|---|---|---|---|
| 2024 | 483 | 8.99 | 9.99 | 8.89 |
| 2025 | 502 | 8.90 | 9.10 | 8.70 |
| 2026 | 324 | 8.99 | 8.99 | 8.99 |
par(mar = c(4.5, 4.5, 3, 1.5))
plot(1:3, basket_tab$Median_all_items, type = "b", pch = 19, ylim = c(8, 10.5),
xaxt = "n", xlab = "", ylab = "Median price (RM)",
main = "Price level: all items vs the same basket")
axis(1, at = 1:3, labels = basket_tab$Year)
lines(1:3, basket_tab$Median_constant_basket, type = "b", pch = 17, col = "#d1495b")
legend("topright", legend = c("All items available each year",
"Same 302 items (constant basket)"),
pch = c(19, 17), col = c("black", "#d1495b"), bty = "n", cex = 0.85)The all-item median is almost flat (grey); the pooled median over the 302 item codes available in all three years falls about 10% (red). The set of codes is fixed, but the weight of each item, state and outlet is not, so this is a pooled-basket median rather than a fixed-weight index.
The pooled basket median falls from RM 9.99 to RM 9.10 to RM 8.99, about 10% between 2024 and 2026 (-8.9% in the first year, then -1.2%), while the all-item median is almost flat (8.99, 8.90, 8.99). Read carefully: this is the median over all records of those 302 codes, so it mixes a true price change with any change in which products, states or outlet types were recorded in greater proportion. What it does support is that the item codes present in all three years did not become more expensive, and that the flat all-item median is partly sustained by a shrinking, and therefore cheaper, item list. It does not support a claim that identical products fell by 10% in every state. Chicken, the most observed fresh item, does not follow the basket path: it went RM 8.89, RM 8.70, then back up to RM 8.99, so the fresh-food channel cannot be described as falling.
A second model removes the item identity analytically. Each price is divided by the national median of its own item, so a RM 30 item and a RM 3 item contribute equally, and the model then estimates how much of that relative price is explained by state, channel, season and year.
imed <- tapply(md$price, md$item_code, median)
md$rel <- md$price / as.numeric(imed[as.character(md$item_code)])
md <- md[is.finite(md$rel) & md$rel > 0, ]
set.seed(25125517)
fit2 <- md[sample.int(nrow(md), 1000000), ]
fit_b <- lm(log(rel) ~ state + premise_type + month + year, data = fit2)
sum_b <- summary(fit_b)
cat("Adjusted R-squared, item-controlled model:", round(sum_b$adj.r.squared, 4), "\n")## Adjusted R-squared, item-controlled model: 0.0582
cb <- summary(fit_b)$coefficients
sel <- c(grep("^state", rownames(cb)), grep("^premise_type", rownames(cb)))
knitr::kable(data.frame(
Term = sub("^state", "State: ", sub("^premise_type", "Outlet: ", rownames(cb)[sel])),
Approx_percent = round(100 * (exp(cb[sel, 1]) - 1), 1),
p_value = format.pval(cb[sel, 4], digits = 3)),
caption = "Item-controlled model: regional and channel effects as percentage differences")| Term | Approx_percent | p_value | |
|---|---|---|---|
| stateKedah | State: Kedah | -1.2 | < 2e-16 |
| stateKelantan | State: Kelantan | -0.7 | 4.87e-09 |
| stateMelaka | State: Melaka | -0.6 | 0.00052 |
| stateNegeri Sembilan | State: Negeri Sembilan | -1.3 | < 2e-16 |
| statePahang | State: Pahang | 1.5 | < 2e-16 |
| statePerak | State: Perak | -1.9 | < 2e-16 |
| statePerlis | State: Perlis | 3.5 | < 2e-16 |
| statePulau Pinang | State: Pulau Pinang | 1.0 | < 2e-16 |
| stateSabah | State: Sabah | 9.3 | < 2e-16 |
| stateSarawak | State: Sarawak | 10.9 | < 2e-16 |
| stateSelangor | State: Selangor | 1.9 | < 2e-16 |
| stateTerengganu | State: Terengganu | 2.9 | < 2e-16 |
| stateW.P. Kuala Lumpur | State: W.P. Kuala Lumpur | 10.3 | < 2e-16 |
| stateW.P. Labuan | State: W.P. Labuan | 13.6 | < 2e-16 |
| stateW.P. Putrajaya | State: W.P. Putrajaya | 8.7 | < 2e-16 |
| premise_typeBorong | Outlet: Borong | -8.6 | 3.25e-08 |
| premise_typeKedai Runcit | Outlet: Kedai Runcit | 8.2 | < 2e-16 |
| premise_typePasar Basah | Outlet: Pasar Basah | 11.4 | < 2e-16 |
| premise_typePasar Mini | Outlet: Pasar Mini | 7.0 | < 2e-16 |
| premise_typePasar Raya / Supermarket | Outlet: Pasar Raya / Supermarket | 1.2 | < 2e-16 |
The item-controlled model agrees on the largest effects and reverses the sign of two channel effects, which is the most interesting result in this report:
Kedai Runcit flips from
-10.3% to +8.2%, and Pasar Mini from -2.9%
to +7.0%. Read together, the two models say that small
shops look cheap mainly because of what they stock; once each
price is measured against that item’s own national median, they sit
above a hypermarket. The gap between the two views is the product-mix
effect, and it is what a single aggregate comparison hides. It remains a
plausible explanation rather than a measured one: the size of the mix
effect would need a category-by-channel cross-tabulation within each
state, which this report does not attempt.The second question turns the price data into a classification problem. Every outlet is labelled:
The features are the outlet’s price level, its state and its item category. The classes are imbalanced in the raw data because the modern group dominates, so a balanced sample of 75,000 rows from each class is drawn: with a balanced design a random guess scores 50%, which is the benchmark every model has to beat. The 70/30 split is drawn at row level, so records from the same outlet can land in both partitions, and the reported accuracy therefore measures discrimination between rows of familiar outlets rather than transfer to an outlet never seen. A strict outlet-level split would score lower; the size of that gap is taken up in the limitations. Because the classes are balanced, accuracy alone can hide a model that recognises one class only, so accuracy, macro-F1 and the two per-class recalls are reported together.
cls <- md[md$premise_type %in% c("Pasar Raya / Supermarket", "Hypermarket",
"Pasar Mini", "Pasar Basah", "Kedai Runcit"), ]
cls$modern <- as.integer(cls$premise_type %in%
c("Pasar Raya / Supermarket", "Hypermarket", "Pasar Mini"))
# short state labels so the tree plot stays readable; the partitions are unchanged
state_abbr <- c("Johor" = "JHR", "Kedah" = "KDH", "Kelantan" = "KTN",
"Melaka" = "MLK", "Negeri Sembilan" = "NSN", "Pahang" = "PHG",
"Perak" = "PRK", "Perlis" = "PLS", "Pulau Pinang" = "PNG",
"Sabah" = "SBH", "Sarawak" = "SWK", "Selangor" = "SGR",
"Terengganu" = "TRG", "W.P. Kuala Lumpur" = "KL",
"W.P. Labuan" = "LBN", "W.P. Putrajaya" = "PJY")
cls$state <- factor(state_abbr[as.character(cls$state)])
set.seed(25125517)
pos <- which(cls$modern == 1); neg <- which(cls$modern == 0)
cls <- cls[c(sample(pos, 75000), sample(neg, 75000)), ]
ti <- sample.int(nrow(cls), round(nrow(cls) * 0.7))
train <- cls[ti, ]; test <- cls[-ti, ]
cat("train rows:", nrow(train), " test rows:", nrow(test), "\n")## train rows: 105000 test rows: 45000
cat("share modern in the training set:", round(mean(train$modern), 3), "\n")## share modern in the training set: 0.501
gl <- glm(modern ~ log(price) + state + item_group, data = train, family = binomial)
pred_gl <- as.integer(predict(gl, newdata = test, type = "response") >= 0.5)
acc_gl <- mean(pred_gl == test$modern)
cat("Logistic regression accuracy on the test set:", round(acc_gl, 4), "\n")## Logistic regression accuracy on the test set: 0.6387
# how much of the signal is carried by the price level alone?
gl_p <- glm(modern ~ log(price), data = train, family = binomial)
acc_p <- mean(as.integer(predict(gl_p, newdata = test, type = "response") >= 0.5)
== test$modern)
cat("Price-only logistic accuracy on the test set:", round(acc_p, 4), "\n")## Price-only logistic accuracy on the test set: 0.5208
rpart grows a tree by choosing, at each step, the split
that most reduces classification impurity. It is included because it
produces a rule that can be read and defended in a presentation, unlike
a black-box model.
suppressMessages(library(rpart))
tree_fit <- rpart(modern ~ price + state + item_group, data = train, method = "class",
control = rpart.control(cp = 0.002, maxdepth = 4, minbucket = 50))
pred_tr <- predict(tree_fit, newdata = test, type = "class")
acc_tr <- mean(as.integer(as.character(pred_tr)) == test$modern)
cat("Decision tree accuracy on the test set:", round(acc_tr, 4), "\n")## Decision tree accuracy on the test set: 0.6627
cat("Leaves in the tree:", sum(tree_fit$frame$var == "<leaf>"), "\n")## Leaves in the tree: 10
imp <- tree_fit$variable.importance
knitr::kable(data.frame(Variable = names(imp),
Importance = round(as.numeric(imp), 0)),
caption = "Variable importance in the decision tree")| Variable | Importance |
|---|---|
| state | 2678 |
| item_group | 1722 |
| price | 1627 |
The tree is capped at four levels on purpose. Deeper trees lifted test accuracy only marginally (a six-level tree reaches 67.2%) while turning the diagram into an unreadable thicket, so the simpler tree is reported: it is the model we can defend in a presentation, and the accuracy difference is not worth the loss of interpretability.
suppressMessages(library(rpart.plot))
rpart.plot(tree_fit, type = 2, extra = 104, fallen.leaves = TRUE,
cex = 0.7, branch = 0.5, split.cex = 0.7,
box.palette = "BuGn", shadow.col = 0,
main = "Decision tree: modern (1) vs traditional (0)")Decision tree for modern versus traditional outlets, drawn with the rpart.plot defaults. Shaded boxes are the predicted class (dark green = modern, blue = traditional) with the share of that class in the node. The root split is on state, item category refines it, and price enters only in the lower levels.
State labels in the figure are abbreviations: JHR Johor, KDH Kedah, KTN Kelantan, MLK Melaka, NSN Negeri Sembilan, PHG Pahang, PRK Perak, PLS Perlis, PNG Pulau Pinang, SBH Sabah, SWK Sarawak, SGR Selangor, TRG Terengganu, KL Kuala Lumpur, LBN Labuan, PJY Putrajaya.
pred_v <- list(
"Logistic regression (price + state + category)" =
as.integer(predict(gl, newdata = test, type = "response") >= 0.5),
"Logistic regression (price only)" =
as.integer(predict(gl_p, newdata = test, type = "response") >= 0.5),
"Decision tree (rpart, maxdepth 4)" =
as.integer(as.character(predict(tree_fit, newdata = test, type = "class")))
)
cm_of <- function(pred, obs)
table(factor(pred, levels = c(0, 1)), factor(obs, levels = c(0, 1)))
macro_f1 <- function(m) {
tp <- diag(m); fp <- colSums(m) - tp; fn <- rowSums(m) - tp
mean(2 * tp / (2 * tp + fp + fn))
}
metrics <- do.call(rbind, lapply(names(pred_v), function(nm) {
m <- cm_of(pred_v[[nm]], test$modern)
data.frame(Model = nm,
Accuracy = round(100 * sum(diag(m)) / sum(m), 1),
Macro_F1 = round(100 * macro_f1(m), 1),
Recall_traditional = round(100 * m["0", "0"] / sum(m[, "0"]), 1),
Recall_modern = round(100 * m["1", "1"] / sum(m[, "1"]), 1))
}))
knitr::kable(metrics, caption = paste0(
"Test-set performance (percent). The design is balanced, so 50 is the random-guess ",
"level; macro-F1 averages the F1 score of both classes equally."))| Model | Accuracy | Macro_F1 | Recall_traditional | Recall_modern |
|---|---|---|---|---|
| Logistic regression (price + state + category) | 63.9 | 63.7 | 69.9 | 57.8 |
| Logistic regression (price only) | 52.1 | 52.1 | 50.6 | 53.6 |
| Decision tree (rpart, maxdepth 4) | 66.3 | 66.3 | 65.4 | 67.1 |
The per-class recalls matter because the classes are balanced: a model that always answers “modern” would already score 50%, and a high overall accuracy can hide a class that is never recognised. The table reports both recalls and the macro-F1 next to the accuracy, so that the headline number cannot stand alone.
cm_tab <- do.call(rbind, lapply(names(pred_v), function(nm) {
m <- cm_of(pred_v[[nm]], test$modern)
data.frame(Model = nm,
Predicted_0_Observed_0 = m["0", "0"],
Predicted_1_Observed_0 = m["1", "0"],
Predicted_0_Observed_1 = m["0", "1"],
Predicted_1_Observed_1 = m["1", "1"],
Misclassified = m["1", "0"] + m["0", "1"])
}))
knitr::kable(cm_tab,
caption = paste0("Confusion matrix counts on the 30% test set. Class 0 = traditional, ",
"class 1 = modern; columns 2-3 are the observed traditional rows, ",
"columns 4-5 the observed modern rows."))| Model | Predicted_0_Observed_0 | Predicted_1_Observed_0 | Predicted_0_Observed_1 | Predicted_1_Observed_1 | Misclassified |
|---|---|---|---|---|---|
| Logistic regression (price + state + category) | 15780 | 6781 | 9479 | 12960 | 16260 |
| Logistic regression (price only) | 11419 | 11142 | 10420 | 12019 | 21562 |
| Decision tree (rpart, maxdepth 4) | 14763 | 7798 | 7382 | 15057 | 15180 |
knitr::kable(data.frame(
Model = c("Logistic regression (price + state + category)",
"Logistic regression (price only)",
"Decision tree (rpart)", "Random guess"),
Accuracy = paste0(round(100 * c(acc_gl, acc_p, acc_tr, 0.5), 1), "%",
c("", "", "", "")),
Lift_over_random = paste0("+", round(100 * c(acc_gl, acc_p, acc_tr, 0.5) - 50, 1),
" points")),
caption = "Classification accuracy on the 30% test set")| Model | Accuracy | Lift_over_random |
|---|---|---|
| Logistic regression (price + state + category) | 63.9% | +13.9 points |
| Logistic regression (price only) | 52.1% | +2.1 points |
| Decision tree (rpart) | 66.3% | +16.3 points |
| Random guess | 50% | +0 points |
The tree wins: 66.3% against 63.9% for the logistic model, both well above the 50% that a balanced random guess would score, and macro-F1 follows the accuracy almost exactly (66.3 against 63.7). The logistic model, however, is visibly asymmetric: it recovers 69.9% of traditional outlets but only 57.8% of modern ones, so it behaves like a detector for the traditional format rather than an even classifier; the tree is balanced (65.4% and 67.1%). The most revealing number in this section, however, is the price-only baseline: on its own, the price level reaches just 52.1%, barely above a coin flip. Almost all of the learning signal therefore sits in where an outlet is and what it stocks, not in how expensive it is. That is the mirror image of the regression coefficients from Section 4.3: channel effects are real, but small next to product mix and location. The variable-importance table agrees, ranking state first, item category second and price third.
The root rule is geographic and worth reading out loud: an outlet in one of ten states (Kedah, Kelantan, Melaka, Negeri Sembilan, Perlis, Pulau Pinang, Perak, Sabah, Selangor, Terengganu) is predicted traditional, with 58% of that branch being wet markets and small shops; outlets in the other six states are predicted modern, with 64% of that branch being hypermarkets, supermarkets or mini markets. Only inside each branch do category and price refine the call, which is why a model that sees only price cannot separate the two groups.
The remaining error is concentrated in mini markets and small provision shops. Mini markets are modern by definition but stock a traditional mix at a traditional price level, so they land on both sides of any price-based rule; a model that only sees price, state and category cannot separate them, and the honest conclusion is that the modern-versus-traditional label is partly a business-format fact rather than something fully visible in prices.
lookup_item, and 273 rows (all in
February 2024, code 20927) because their premise code is
not in lookup_premise. The monthly missing rate runs from
0.97% to 2.56%. The dropped rows carry no category, state or outlet
metadata that survived the join, so whether they differ systematically
from the kept rows cannot be tested from this data alone.item_code x state groups, 801 contain fewer than 20
observations, 479 fewer than 10, 262 fewer than 5 and 105 a single
observation; the interquartile filter is unreliable at those sizes, and
it trims the same 2.85% everywhere rather than adapting to group size.
The filter threshold is also estimated on the same sample that is later
modelled, so the test accuracy is not fully out-of-sample.Borong contributes only 749
records (0.02%) and is kept in the model as a level shift without
separate interpretation.Using 35 months of the official PriceCatcher series (74.1 million raw records in four columns, 72.6 million kept after the lookup filter, seven analysis variables after the join, and a 5% modelling sample), this report answered two questions. On the first, the level of a retail price is mostly a matter of where and through what channel the sale happens: Labuan and Kuala Lumpur sit around 13-15% above Johor, wet markets around 8% above a hypermarket, and small shops around 10% below it, while comparing the 302 item codes that appear in all three years shows their pooled median about 10% lower in 2026 than in 2024. On the second, a decision tree separates modern from traditional outlets at 66% test accuracy, but the price on its own reaches only 52%, which says that the retail format is a geographic and product-mix fact rather than a price fact.
Three practical readings follow. Comparisons across years must pin the basket, because the monitored item list changes and an unpinned median hides real price movements. Geography, not shop type, is the dominant price factor and survives item control. And “traditional retail” should not be treated as one policy category, since wet markets and small shops move in opposite directions.
The main limitation is scope: PriceCatcher is a monitored sample of premises, not a census or a cost-of-living index, the 2026 files stop in November, prices are recorded per unit rather than per standardised unit, and the models are fitted on a 5% sample with row-level splits. The full list is in the limitations section above. Within those bounds, the cleaning pipeline in Section 3 is reproducible from the raw files with the R code shown in this document.
data.gov.my: https://data.gov.my/data-catalogue/pricecatcherhttps://storage.data.gov.my/pricecatcher/pricecatcher_YYYY-MM.csvcat("Analysis completed:", format(Sys.time(), "%Y-%m-%d %H:%M"), "\n")## Analysis completed: 2026-11-26 22:01
cat("R version:", R.version.string, "\n")## R version: R version 4.6.1 (2026-06-24 ucrt)
cat("Monthly files processed:", nrow(rec), "\n")## Monthly files processed: 35