# Load library
library(randomForest)
## Warning: package 'randomForest' was built under R version 4.5.2
## randomForest 4.7-1.2
## Type rfNews() to see new features/changes/bug fixes.
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.5.2
##
## Attaching package: 'dplyr'
## The following object is masked from 'package:randomForest':
##
## combine
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(lubridate)
## Warning: package 'lubridate' was built under R version 4.5.2
##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
library(ggplot2)
##
## Attaching package: 'ggplot2'
## The following object is masked from 'package:randomForest':
##
## margin
library(Metrics)
## Warning: package 'Metrics' was built under R version 4.5.3
data <- read.csv("data_mts.csv")
# Periksa beberapa baris pertama data
head(data)
## tanggal penjualan suhu harga pengunjung
## 1 2023-01-01 200.00 28.00 50.00 500.00
## 2 2023-01-02 206.56 28.05 50.02 531.72
## 3 2023-01-03 208.31 27.08 51.80 551.55
## 4 2023-01-04 204.23 29.19 52.01 511.91
## 5 2023-01-05 200.40 27.36 52.98 485.06
## 6 2023-01-06 193.51 27.37 54.07 466.07
str(data)
## 'data.frame': 1000 obs. of 5 variables:
## $ tanggal : chr "2023-01-01" "2023-01-02" "2023-01-03" "2023-01-04" ...
## $ penjualan : num 200 207 208 204 200 ...
## $ suhu : num 28 28.1 27.1 29.2 27.4 ...
## $ harga : num 50 50 51.8 52 53 ...
## $ pengunjung: num 500 532 552 512 485 ...
# 3. Feature Engineering Sesuai Karakteristik Soal
data_clean <- data %>%
mutate(tanggal = as.Date(tanggal)) %>%
arrange(tanggal) %>%
mutate(
# [POLA 1: TREN NAIK] -> Tambahkan indeks waktu berurutan
trend_index = row_number(),
# [POLA 2: SIKLUS MINGGUAN (Jumat Paling Sepi)] -> Faktor nama hari
nama_hari = factor(wday(tanggal, label = TRUE, abbr = FALSE, week_start = 1)),
is_jumat = ifelse(wday(tanggal, week_start = 1) == 5, 1, 0), # Flag khusus Jumat
# [POLA 3: MUSIMAN TAHUNAN] -> Bulan dan hari ke-n dalam setahun
bulan = month(tanggal),
hari_thn = yday(tanggal),
# [TIME SERIES AUTOREGRESSIVE] -> Penjualan kemarin & minggu lalu
penjualan_lag1 = lag(penjualan, 1), # H-1
penjualan_lag7 = lag(penjualan, 7) # H-7 (siklus mingguan yang sama)
) %>%
# Hapus baris NA akibat lag 7 hari pertama
na.omit()
# 4. Pembagian Data Train dan Test (80% Train, 20% Test)
# Data Time Series dibagi berurutan (tidak di-shuffle/acak)
proporsi_train <- 0.8
n_train <- floor(nrow(data_clean) * proporsi_train)
data_train <- data_clean[1:n_train, ]
data_test <- data_clean[(n_train + 1):nrow(data_clean), ]
cat("Rentang Data Latih (Train):", as.character(min(data_train$tanggal)), "sampai", as.character(max(data_train$tanggal)), "\n")
## Rentang Data Latih (Train): 2023-01-08 sampai 2025-03-11
cat("Rentang Data Uji (Test) :", as.character(min(data_test$tanggal)), "sampai", as.character(max(data_test$tanggal)), "\n")
## Rentang Data Uji (Test) : 2025-03-12 sampai 2025-09-26
cat("Jumlah baris train:", nrow(data_train), "| Jumlah baris test:", nrow(data_test), "\n\n")
## Jumlah baris train: 794 | Jumlah baris test: 199
# 5. Formula Model: Variabel Multivariat + Fitur Pola Waktu
formula_rf <- penjualan ~ suhu + harga + pengunjung +
trend_index + # <-- Tambahkan ini (Pola Tren)
nama_hari + is_jumat + # <-- Tambahkan ini (Pola Jumat Sepi)
bulan + hari_thn + # <-- Tambahkan hari_thn (Pola Musiman Tahunan)
penjualan_lag1 + penjualan_lag7
# 6. Melatih Model Random Forest
set.seed(42) # Menjaga reproduktibilitas hasil
model_rf <- randomForest(
formula = formula_rf,
data = data_train,
ntree = 500, # Banyak pohon keputusan
mtry = 3, # Banyak variabel acak tiap split node
importance = TRUE
)
# Tampilkan ringkasan model
print(model_rf)
##
## Call:
## randomForest(formula = formula_rf, data = data_train, ntree = 500, mtry = 3, importance = TRUE)
## Type of random forest: regression
## Number of trees: 500
## No. of variables tried at each split: 3
##
## Mean of squared residuals: 42.7152
## % Var explained: 84.04
# 7. Melakukan Prediksi pada Data Uji (Test Set)
prediksi_test <- predict(model_rf, newdata = data_test)
# 8. Evaluasi Akurasi Model
actual <- data_test$penjualan
rmse_score <- rmse(actual, prediksi_test)
mae_score <- mae(actual, prediksi_test)
r2_score <- 1 - (sum((actual - prediksi_test)^2) / sum((actual - mean(actual))^2))
cat("================ HASIL EVALUASI MODEL ================\n")
## ================ HASIL EVALUASI MODEL ================
cat(sprintf("RMSE (Root Mean Squared Error) : %.4f\n", rmse_score))
## RMSE (Root Mean Squared Error) : 8.5485
cat(sprintf("MAE (Mean Absolute Error) : %.4f\n", mae_score))
## MAE (Mean Absolute Error) : 6.5801
cat(sprintf("R-squared (R²) : %.4f (%.2f%%)\n", r2_score, r2_score * 100))
## R-squared (R²) : 0.6118 (61.18%)
cat("======================================================\n\n")
## ======================================================
# 9. Visualisasi Grafik: Nilai Aktual vs Nilai Prediksi
df_plot <- data_test %>%
select(tanggal, penjualan) %>%
mutate(prediksi = prediksi_test)
plot_pred <- ggplot(df_plot, aes(x = tanggal)) +
geom_line(aes(y = penjualan, color = "Aktual"), linewidth = 0.9) +
geom_line(aes(y = prediksi, color = "Prediksi RF"), linewidth = 0.9, linetype = "dashed") +
labs(
title = "Time Series Forecasting: Penjualan Aktual vs Prediksi Random Forest",
subtitle = paste("Periode Data Test:", min(df_plot$tanggal), "s/d", max(df_plot$tanggal)),
x = "Tanggal",
y = "Jumlah Penjualan",
color = "Keterangan"
) +
scale_color_manual(values = c("Aktual" = "#1f77b4", "Prediksi RF" = "#d62728")) +
theme_minimal(base_size = 12) +
theme(legend.position = "top")
print(plot_pred)

# 10. Visualisasi Feature Importance (Variabel yang Paling Berpengaruh)
importance_df <- data.frame(
Feature = rownames(importance(model_rf)),
IncMSE = importance(model_rf)[, "%IncMSE"]
)
plot_imp <- ggplot(importance_df, aes(x = reorder(Feature, IncMSE), y = IncMSE)) +
geom_col(fill = "steelblue") +
coord_flip() +
labs(
title = "Tingkat Kepentingan Variabel (Feature Importance)",
x = "Variabel Prediktor",
y = "% Kenaikan MSE jika Variabel Dihilangkan (%IncMSE)"
) +
theme_minimal(base_size = 12)
print(plot_imp)

# Grafik Boxplot Rata-rata Penjualan per Hari (Sudah Diperbaiki)
ggplot(data_clean, aes(x = nama_hari, y = penjualan, fill = (nama_hari == "Friday"))) +
geom_boxplot(alpha = 0.8, outlier.color = "red") +
scale_fill_manual(values = c("FALSE" = "#6baed6", "TRUE" = "#e6550d"),
labels = c("Hari Lain", "Jumat (Paling Sepi)"),
name = "Kategori Hari") +
labs(
title = "Verifikasi Pola Siklus Mingguan: Rata-rata Penjualan per Hari",
subtitle = "Terbukti penjualan pada hari Jumat mengalami penurunan paling signifikan",
x = "Hari",
y = "Penjualan (unit/hari)"
) +
theme_minimal(base_size = 12) +
theme(legend.position = "top")
