library(ggplot2) #untuk visualisasi data
library(reshape2) #untuk mengubah matrix ke format long, dan sebaliknya
data <- datasets::mtcars
data_mtcars <- data[, c("mpg", "disp", "hp", "wt", "qsec")]
#Matriks Korelasi
cor_mtcars <- cor(data_mtcars) #untuk menghitung korelasi
cor_mtcars
## mpg disp hp wt qsec
## mpg 1.0000000 -0.8475514 -0.7761684 -0.8676594 0.4186840
## disp -0.8475514 1.0000000 0.7909486 0.8879799 -0.4336979
## hp -0.7761684 0.7909486 1.0000000 0.6587479 -0.7082234
## wt -0.8676594 0.8879799 0.6587479 1.0000000 -0.1747159
## qsec 0.4186840 -0.4336979 -0.7082234 -0.1747159 1.0000000
#Heatmap
data_cor <- melt(cor_mtcars) #melt = mengubah struktur data dari bentuk lebar (wide) menjadi bentuk panjang (long)
ggplot(data_cor, aes(Var1, Var2, fill = value)) +
geom_tile(color = "black") +
geom_text(aes(label = round(value, 2)), color = "black")+ #round value 2 untuk membulatkan 2 angka di belkang koma
scale_fill_gradient2(low = "red", high = "green", mid = "yellow",
midpoint = 0, limit = c(-1, 1), name = "Korelasi") +
theme_minimal() +
labs(title = "Heatmap Dataset mtcars",
x = "Variabel 1", y= "Variabel 2") +
theme(plot.title = element_text(hjust = 0.5),
axis.text.x = element_text(hjust = 0.5))
#Distribusi Bernoulli
bern <- function(x,p) {p^x*(1-p)^(1-x)}
bern(1,3/6)
## [1] 0.5
#Distribusi Binomial
cmfbinom <- function(k, n, p) { #cmfbinom itu untuk menghitung peluang komulatif binomial
# Validasi Input
if (k < 0 || n < 0 || p < 0 || p > 1) {
stop("Input Tidak Valid")
}
# Inisialisasi CMF
cmf <- 0
# Menghitung CMF
for (x in 0:k) {
prob <- choose(n, x) * (p^x) * ((1 - p)^(n - x))
cmf <- cmf + prob
}
return(cmf)
}
# Peluang paling sedikit 2 orang sembuh = 1 - P(X ≤ 1)
Peluang = 1 - cmfbinom(1, 12, 0.2)
Peluang
## [1] 0.7251221
#Distribusi Poissom
cmfpois <- function(x, lambda) {
if (lambda <= 0) {
stop("Lambda Harus Bernilai > 0")
}
if (x < 0) {
return(0)
}
cmf <- 0 #tempat menyimpan total penjumlahan peluang
for (k in 0:x) { #melakukan perulangan (loop) mulai dari k = 0 sampai k = x.
cmf <- cmf + (exp(-lambda) * (lambda^k) / factorial(k))
}
return(cmf)
}
Peluang2 <- cmfpois(10, 2) - cmfpois(0, 2)
Peluang2
## [1] 0.8646564
#Distribusi Geometrik
geo <- function(x,p){p*(1-p)^(x-1)}
geo(5,0.3)
## [1] 0.07203
#Distribusi Hipergeometrik
hyper<-function(x,N,n,k){(((factorial(k)/(factorial(k-x) * factorial(x))) * (factorial(N-k)/((factorial((N-k)-(n-x))) * (factorial(n-x)))))/(factorial(N)/(factorial(N-n)*factorial(n))))}
hyper(2,100,10,5)
## [1] 0.07021881