# 1. MEMUAT PACKAGE DAN DATA
library(ggplot2)
library(lmtest)
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
library(car)
## Loading required package: carData
# Baca data dari Excel (CSV)
data <- read.csv("C:/Users/ACER/Downloads/best sellin books 2023.csv")

# 2. ANALISIS DESKRIPTIF DAN VISUALISASI
print("Statistik Deskriptif:")
## [1] "Statistik Deskriptif:"
summary(data)
##       id             Book.name            Author             Rating         
##  Length:100         Length:100         Length:100         Length:100        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##  reviews.count        form              price           Reading.age       
##  Min.   :  3296   Length:100         Length:100         Length:100        
##  1st Qu.: 26168   Class :character   Class :character   Class :character  
##  Median : 77085   Mode  :character   Mode  :character   Mode  :character  
##  Mean   :111733                                                           
##  3rd Qu.:129236                                                           
##  Max.   :653111                                                           
##                                                                           
##   Print.Length    Publishing.date       Genre          
##  Min.   :  24.0   Length:100         Length:100        
##  1st Qu.: 208.0   Class :character   Class :character  
##  Median : 344.0   Mode  :character   Mode  :character  
##  Mean   : 361.2                                        
##  3rd Qu.: 448.0                                        
##  Max.   :2896.0                                        
##  NA's   :2
#Seleksi dan Pembersihan Variabel
names(data)
##  [1] "id"              "Book.name"       "Author"          "Rating"         
##  [5] "reviews.count"   "form"            "price"           "Reading.age"    
##  [9] "Print.Length"    "Publishing.date" "Genre"
str(data$reviews.count)
##  int [1:100] 145747 395512 116101 472618 51520 322650 87375 82564 228242 19946 ...
str(data$Rating)
##  chr [1:100] "4.8 out of 5 stars" "4.7 out of 5 stars" "4.5 out of 5 stars" ...
data$Rating_num <- as.numeric(gsub("[^0-9\\.]", "", data$Rating))
str(data$Rating_num)
##  num [1:100] 4.85 4.75 4.55 4.85 4.45 4.65 4.75 4.85 4.55 4.65 ...
summary(data$Rating_num)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##    4.15    4.55    4.75    4.70    4.85    4.95
data2 <- na.omit(data[, c("reviews.count", "Rating_num")])


# Scatter plot
ggplot(data, aes(x = reviews.count, y = Rating_num)) +
  geom_point(color = "blue", size = 3) +
  labs(title = "Hubungan Jumlah Review dan Rating",
       x = "Jumlah Review", y = "Rating") +
  theme_minimal()

# Korelasi
cor_test <- cor.test(data$reviews.count, data$Rating_num)
print(paste("Korelasi Pearson:", round(cor_test$estimate, 4)))
## [1] "Korelasi Pearson: -0.2333"
print(paste("p-value korelasi:", round(cor_test$p.value, 4)))
## [1] "p-value korelasi: 0.0195"
# 3. MEMBANGUN MODEL REGRESI
model <- lm(Rating_num ~ reviews.count, data = data)
print("Ringkasan Model Regresi:")
## [1] "Ringkasan Model Regresi:"
summary(model)
## 
## Call:
## lm(formula = Rating_num ~ reviews.count, data = data)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.56430 -0.10613  0.04451  0.13032  0.28251 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)    4.741e+00  2.566e-02 184.777   <2e-16 ***
## reviews.count -3.672e-07  1.546e-07  -2.375   0.0195 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.1897 on 98 degrees of freedom
## Multiple R-squared:  0.05442,    Adjusted R-squared:  0.04477 
## F-statistic:  5.64 on 1 and 98 DF,  p-value: 0.0195
# 4. UJI ASUMSI REGRESI LINEAR
cat("\n=== UJI ASUMSI REGRESI LINEAR ===\n")
## 
## === UJI ASUMSI REGRESI LINEAR ===
# 4.1 Normalitas Residual
shapiro_test <- shapiro.test(residuals(model))
cat("1. UJI NORMALITAS (Shapiro-Wilk):\n")
## 1. UJI NORMALITAS (Shapiro-Wilk):
cat("   Statistik W =", round(shapiro_test$statistic, 4), "\n")
##    Statistik W = 0.9219
cat("   p-value =", round(shapiro_test$p.value, 4), "\n")
##    p-value = 0
if(shapiro_test$p.value > 0.05) {
  cat("   Keputusan: Residual berdistribusi normal\n")
} else {
  cat("   Keputusan: Residual tidak normal\n")
}
##    Keputusan: Residual tidak normal
# Q-Q Plot
qqnorm(residuals(model), main = "Q-Q Plot Residual")
qqline(residuals(model), col = "red")

# 4.2 Homoskedastisitas
bp_test <- bptest(model)
cat("\n2. UJI HOMOSKEDASTISITAS (Breusch-Pagan):\n")
## 
## 2. UJI HOMOSKEDASTISITAS (Breusch-Pagan):
cat("   Statistik LM =", round(bp_test$statistic, 4), "\n")
##    Statistik LM = 0.0065
cat("   p-value =", round(bp_test$p.value, 4), "\n")
##    p-value = 0.9359
if(bp_test$p.value > 0.05) {
  cat("   Keputusan: Varian residual homogen\n")
} else {
  cat("   Keputusan: Ada heteroskedastisitas\n")
}
##    Keputusan: Varian residual homogen
# Plot Residual vs Fitted
plot(fitted(model), residuals(model),
     main = "Residual vs Fitted Values",
     xlab = "Fitted Values", ylab = "Residuals",
     pch = 19, col = "blue")
abline(h = 0, col = "red", lty = 2)

# 4.3 Tidak ada Autokorelasi
dw_test <- dwtest(model)
cat("\n3. UJI AUTOKORELASI (Durbin-Watson):\n")
## 
## 3. UJI AUTOKORELASI (Durbin-Watson):
cat("   Statistik DW =", round(dw_test$statistic, 4), "\n")
##    Statistik DW = 2.159
cat("   p-value =", round(dw_test$p.value, 4), "\n")
##    p-value = 0.7858
if(dw_test$p.value > 0.05) {
  cat("   Keputusan: Tidak ada autokorelasi\n")
} else {
  cat("   Keputusan: Ada autokorelasi\n")
}
##    Keputusan: Tidak ada autokorelasi
# 5. INTERPRETASI KOEFISIEN
cat("\n=== INTERPRETASI KOEFISIEN ===\n")
## 
## === INTERPRETASI KOEFISIEN ===
intercept <- coef(model)[1]
slope <- coef(model)[2]

cat("Persamaan Regresi: Rating =", round(intercept, 2), "+", round(slope, 2), "* Jumlah_Review\n")
## Persamaan Regresi: Rating = 4.74 + 0 * Jumlah_Review
cat("\nInterpretasi:\n")
## 
## Interpretasi:
cat("1. Intercept (β0 =", round(intercept, 2), "):\n")
## 1. Intercept (β0 = 4.74 ):
cat("   Rating yang diprediksi ketika jumlah review = 0 adalah", round(intercept, 2), "poin\n")
##    Rating yang diprediksi ketika jumlah review = 0 adalah 4.74 poin
cat("2. Slope (β1 =", round(slope, 2), "):\n")
## 2. Slope (β1 = 0 ):
cat("   Setiap penambahan 1 review, rating diperkirakan berubah sebesar", round(slope, 2), "poin\n")
##    Setiap penambahan 1 review, rating diperkirakan berubah sebesar 0 poin
# 6. ESTIMASI PARAMETER DAN INFERENSI
cat("\n=== ESTIMASI PARAMETER ===\n")
## 
## === ESTIMASI PARAMETER ===
conf_int <- confint(model, level = 0.95)
cat("Interval Kepercayaan 95%:\n")
## Interval Kepercayaan 95%:
cat("   Intercept: [", round(conf_int[1,1], 3), ", ", round(conf_int[1,2], 3), "]\n", sep = "")
##    Intercept: [4.69, 4.792]
cat("   Slope:     [", round(conf_int[2,1], 3), ", ", round(conf_int[2,2], 3), "]\n", sep = "")
##    Slope:     [0, 0]
# Uji hipotesis untuk slope
cat("\nUji Hipotesis untuk Slope (β1):\n")
## 
## Uji Hipotesis untuk Slope (β1):
cat("   H0: β1 = 0 (tidak ada hubungan linear)\n")
##    H0: β1 = 0 (tidak ada hubungan linear)
cat("   H1: β1 ≠ 0 (ada hubungan linear)\n")
##    H1: β1 ≠ 0 (ada hubungan linear)
summary_model <- summary(model)
slope_pvalue <- summary_model$coefficients[2, 4]
cat("   p-value =", round(slope_pvalue, 6), "\n")
##    p-value = 0.019505
if(slope_pvalue < 0.05) {
  cat("   Keputusan: Tolak H0, ada hubungan linear signifikan\n")
} else {
  cat("   Keputusan: Gagal tolak H0, tidak ada hubungan linear signifikan\n")
}
##    Keputusan: Tolak H0, ada hubungan linear signifikan
# 7. KOEFISIEN DETERMINASI
r_squared <- summary_model$r.squared
cat("\nKoefisien Determinasi (R²):\n")
## 
## Koefisien Determinasi (R²):
cat("   R² =", round(r_squared, 4), "\n")
##    R² = 0.0544
cat("   Artinya:", round(r_squared * 100, 2), "% variasi rating buku dapat dijelaskan oleh jumlah review\n")
##    Artinya: 5.44 % variasi rating buku dapat dijelaskan oleh jumlah review
# 8. VISUALISASI MODEL
ggplot(data, aes(x = reviews.count, y = Rating)) +
  geom_point(color = "blue", size = 3) +
  geom_smooth(method = "lm", se = TRUE, color = "red", fill = "pink") +
  labs(title = "Garis Regresi Linear(Hubungan Jumlah Review dan Rating Buku)",
       subtitle = paste("Y =", round(intercept, 2), "+", round(slope, 2), "X"),
       x = "Jumlah Review", y = "Rating Buku") +
  theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'
## Warning in qt((1 - level)/2, df): NaNs produced
## Warning in max(ids, na.rm = TRUE): no non-missing arguments to max; returning
## -Inf

# 9. PREDIKSI
new_data <- data.frame(reviews.count = c(12, 15))
prediction <- predict(model, newdata = new_data, interval = "confidence")
cat("\n=== PREDIKSI ===\n")
## 
## === PREDIKSI ===
cat("Untuk 50.000 review, prediksi rating =", round(prediction[1, "fit"], 2), "\n")
## Untuk 50.000 review, prediksi rating = 4.74
cat("Untuk 200.000 review, prediksi rating =", round(prediction[2, "fit"], 2), "\n")
## Untuk 200.000 review, prediksi rating = 4.74
# 10. DIAGNOSTIC PLOTS
par(mfrow = c(2, 2))
plot(model, which = 1:4)

par(mfrow = c(1, 1))

# 11. RINGKASAN LENGKAP
cat("\n=== RINGKASAN ANALISIS ===\n")
## 
## === RINGKASAN ANALISIS ===
cat("1. Model: Nilai_Ujian = β0 + β1*Jumlah_Review + ε\n")
## 1. Model: Nilai_Ujian = β0 + β1*Jumlah_Review + ε
cat("2. Estimasi: Y =", round(intercept, 3), "+", round(slope, 3), "* X\n")
## 2. Estimasi: Y = 4.741 + 0 * X
cat("3. R² =", round(r_squared, 4), "(", round(r_squared*100, 1), "%)\n")
## 3. R² = 0.0544 ( 5.4 %)
cat("4. Uji F (model): p-value =", 
    round(summary_model$fstatistic[1], 4), "\n")
## 4. Uji F (model): p-value = 5.6398
cat("5. Asumsi:\n")
## 5. Asumsi:
cat("   - Normalitas: p =", round(shapiro_test$p.value, 4), "\n")
##    - Normalitas: p = 0
cat("   - Homoskedastisitas: p =", round(bp_test$p.value, 4), "\n")
##    - Homoskedastisitas: p = 0.9359
cat("   - Autokorelasi: p =", round(dw_test$p.value, 4), "\n")
##    - Autokorelasi: p = 0.7858
# Simpan hasil
hasil <- list(
  model = model,
  coefficients = coef(model),
  r_squared = r_squared,
  assumptions = list(
    normality = shapiro_test$p.value,
    homoscedasticity = bp_test$p.value,
    autocorrelation = dw_test$p.value
  ),
  confidence_intervals = conf_int
)

print("Analisis regresi linear sederhana selesai!")
## [1] "Analisis regresi linear sederhana selesai!"