setClass("RegresiLinear",
slots = list(
X = "matrix",
y = "numeric",
coef = "numeric"
))
RegresiLinear <- function(X, y) {
X <- as.matrix(X)
n <- nrow(X)
p <- ncol(X)
X_aug <- cbind(1, X) # intercept
# Fungsi loss (MSE)
loss_fn <- function(beta) {
y_hat <- X_aug %*% beta
sum((y - y_hat)^2)
}
# Optimisasi
beta_init <- rep(0, ncol(X_aug))
est <- optim(par = beta_init, fn = loss_fn)
coef <- est$par
new("RegresiLinear", X = X_aug, y = y, coef = coef)
}
setGeneric("getCoef", function(object) standardGeneric("getCoef"))
## [1] "getCoef"
setMethod("getCoef", "RegresiLinear", function(object) {
object@coef
})
setGeneric("predict", function(object, newdata) standardGeneric("predict"))
## Creating a new generic function for 'predict' in the global environment
## [1] "predict"
setMethod("summary", "RegresiLinear", function(object) {
cat("Koefisien Model:\n")
print(object@coef)
})
setMethod("plot", "RegresiLinear", function(x, y, ...) {
y_hat <- x@X %*% x@coef
plot(x@y, y_hat, main = "Fitted vs Actual", xlab = "Actual", ylab = "Fitted")
abline(0, 1, col = "red")
})
setGeneric("residuals")
## [1] "residuals"
setMethod("residuals", "RegresiLinear", function(object) {
object@y - object@X %*% object@coef
})
setClass("RegresiPolinomial",
contains = "RegresiLinear")
RegresiPolinomial <- function(x, y, degree = 2) {
X_poly <- sapply(1:degree, function(d) x^d)
model <- RegresiLinear(X_poly, y)
new("RegresiPolinomial", X = model@X, y = model@y, coef = model@coef)
}
# Buat folder utama package
dir.create("RegresiModel")
dir.create("RegresiModel/R")
dir.create("RegresiModel/man")
description_content <- "
Package: RegresiModel
Type: Package
Title: Pemodelan Regresi dengan S4
Version: 0.1.0
Author: Nandito Hernawan
Maintainer: Nandito Hernawan <nanditohernawan31@gmail.com>
Description: Implementasi regresi linier dan polinomial menggunakan sistem OOP S4.
License: MIT
Encoding: UTF-8
LazyData: true"
writeLines(description_content, "RegresiModel/DESCRIPTION")
# Buat file NAMESPACE
namespace_content <- "
exportClasses(RegresiLinear, RegresiPolinomial)
exportMethods(getCoef, predict, summary, plot, residuals)
export(RegresiLinear, RegresiPolinomial)"
writeLines(trimws(namespace_content), "RegresiModel/NAMESPACE")
writeLines('
setClass("RegresiLinear",
slots = list(
X = "matrix",
y = "numeric",
coef = "numeric"
))
RegresiLinear <- function(X, y) {
X <- as.matrix(X)
X_aug <- cbind(1, X)
loss_fn <- function(beta) {
y_hat <- X_aug %*% beta
sum((y - y_hat)^2)
}
beta_init <- rep(0, ncol(X_aug))
est <- optim(par = beta_init, fn = loss_fn)
coef <- est$par
new("RegresiLinear", X = X_aug, y = y, coef = coef)
}
', "RegresiModel/R/class_linear.R")
writeLines('
setGeneric("getCoef", function(object) standardGeneric("getCoef"))
setMethod("getCoef", "RegresiLinear", function(object) {
object@coef
})
setGeneric("predict", function(object, newdata) standardGeneric("predict"))
setMethod("summary", "RegresiLinear", function(object) {
cat("Koefisien Model:\n")
print(object@coef)
})
setMethod("plot", "RegresiLinear", function(x, y, ...) {
y_hat <- x@X %*% x@coef
plot(x@y, y_hat, main = "Fitted vs Actual", xlab = "Actual", ylab = "Fitted")
abline(0, 1, col = "red")
})
setGeneric("residuals")
setMethod("residuals", "RegresiLinear", function(object) {
object@y - object@X %*% object@coef
})
', "RegresiModel/R/methods_linear.R")
writeLines('
setClass("RegresiPolinomial",
contains = "RegresiLinear")
RegresiPolinomial <- function(x, y, degree = 2) {
X_poly <- sapply(1:degree, function(d) x^d)
model <- RegresiLinear(X_poly, y)
new("RegresiPolinomial", X = model@X, y = model@y, coef = model@coef)
}
', "RegresiModel/R/class_polynomial.R")
library(devtools)
## Warning: package 'devtools' was built under R version 4.4.3
## Loading required package: usethis
## Warning: package 'usethis' was built under R version 4.4.3
document("RegresiModel")
## ℹ Updating RegresiModel documentation
## First time using roxygen2. Upgrading automatically...
## Setting `RoxygenNote` to "7.3.2"
## ℹ Loading RegresiModel
## Creating a new generic function for 'predict' in package 'RegresiModel'
## Warning: ── Conflicts ───────────────────────────────────────── RegresiModel conflicts
## ──
## ✖ `getCoef` masks `RegresiModel::getCoef()`.
## ✖ `predict` masks `RegresiModel::predict()`.
## ✖ `RegresiLinear` masks `RegresiModel::RegresiLinear()`.
## … and more.
## ℹ Did you accidentally source a file rather than using `load_all()`?
## Run `rm(list = c("getCoef", "predict", "RegresiLinear", "RegresiPolinomial",
## "residuals"))` to remove the conflicts.
## ✖ Skipping 'NAMESPACE'
## ℹ It already exists and was not generated by roxygen2.
install("RegresiModel")
## ── R CMD build ─────────────────────────────────────────────────────────────────
## checking for file 'C:\Users\LENOVO\Downloads\RegresiModel/DESCRIPTION' ... ✔ checking for file 'C:\Users\LENOVO\Downloads\RegresiModel/DESCRIPTION'
## ─ preparing 'RegresiModel':
## ✔ checking DESCRIPTION meta-information
## ─ checking for LF line-endings in source and make files and shell scripts
## ─ checking for empty or unneeded directories
## Removed empty directory 'RegresiModel/man'
## Omitted 'LazyData' from DESCRIPTION
## ─ building 'RegresiModel_0.1.0.tar.gz'
##
## Running "C:/PROGRA~1/R/R-44~1.1/bin/x64/Rcmd.exe" INSTALL \
## "C:\Users\LENOVO\AppData\Local\Temp\Rtmp08tpZL/RegresiModel_0.1.0.tar.gz" \
## --install-tests
## * installing to library 'C:/Users/LENOVO/AppData/Local/R/win-library/4.4'
## * installing *source* package 'RegresiModel' ...
## ** using staged installation
## ** R
## ** byte-compile and prepare package for lazy loading
## Creating a new generic function for 'predict' in package 'RegresiModel'
## ** help
## No man pages found in package 'RegresiModel'
## *** installing help indices
## ** building package indices
## ** testing if installed package can be loaded from temporary location
## ** testing if installed package can be loaded from final location
## ** testing if installed package keeps a record of temporary installation path
## * DONE (RegresiModel)
##
## Attaching package: 'RegresiModel'
##
## The following objects are masked _by_ '.GlobalEnv':
##
## getCoef, predict, RegresiLinear, RegresiPolinomial
##
## The following object is masked from 'package:stats':
##
## predict
library(RegresiModel)