Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 27

LAPORAN KOMPUTASI II

PEMROGRAMAN R STUDIO

Dosen Pengajar : Oni Soesanto, S.Si, M.Si

NAMA :

DEDY HARDIANSYAH 1811017310017

NABILA SEPTIANI 1811017320020

SYIFA URRAHMAH 1811017320010

PROGRAM STUDI STATISTIKA

FAKULTAS MATEMATIKA DAN ILMU PENGETAHUAN ALAM

UNIVERSITAS LAMBUNG MANGKURAT

TAHUN AJARAN 2019/2020


BAB III
Basic Programming
3.1 Introduction
3.1.1 Example: roots of a quadratic 1 quad1.r
Scripts :
input
a2 <- 1
a1 <- 4
a0 <- 2
calculation
root1 <- (-a1 + sqrt(a1^2 - 4*a2*a0))/(2*a2)
root2 <- (-a1 - sqrt(a1^2 - 4*a2*a0))/(2*a2)
output
print(c(root1, root2))

Hasil :

3.2 Branching with if


3.2.1 Example: roots of a quadratic 2 quad2.r
Scripts :
input
a2 <- 1
a1 <- 4
a0 <- 5
calculate the discriminant
discrim <- a1^2 - 4*a2*a0
calculate the roots depending on the value of the discriminant
if (discrim > 0)
{ roots <- c( (-a1 + sqrt(a1^2 - 4*a2*a0))/(2*a2),
(-a1 - sqrt(a1^2 - 4*a2*a0))/(2*a2) ) }
else
{ if (discrim == 0)
{ roots <- -a1/(2*a2) }
else
{ roots <- c() } }
output
show(roots)

Hasil :

3.3 Looping with for


3.3.1 Example: summing a vector
Scripts :
(x_list <- seq(1, 9, by = 2))
sum_x <- 0
for (x in x_list)
sum_x + x +
cat("The current loop element is", x, "\n")
cat("The cumulative total is", sum_x, "\n")
sum(x_list)
Hasil :

3.3.2 Example: n factorial 1 nfact1.r


Scripts :
Input
n <- 6
n_factorial <- 1
for (i in 1:n)
{ n_factorial <- n_factorial * i }
show(n_factorial)

Hasil :
3.3.3 Example: pension value pension.r
Scripts :
Inputs
r <- 0.11
term <- 10
period <- 1/12
payments <- 100
n <- floor(term/period)
pension <- 0
for (i in 1:n) { pension[i+1] <- pension[i]*(1 + r*period) + payments }
time <- (0:n)*period
Output
plot(time, pension)

Hasil :

3.4 Looping with while


3.4.1 Example: Fibonacci numbers fibonacci.r
Scripts :
initialise variables
F <- c(1, 1)
n <- 2
iteratively calculate new Fibonacci numbers
while (F[n] <= 100)
{cat("n =", n, " F[n] =", F[n], "\n")
n <- n + 1
F[n] <- F[n-1] + F[n-2]}
output
cat("The first Fibonacci number > 100 is F(", n, ") =", F[n], "\n")
Hasil :

3.4.2 Example: compound interest compound.r


Scripts :
Inputs
r <- 0.11
period <- 1/12
debt_initial <- 1000
repayments <- 12
Calculations
time <- 0
debt <- debt_initial
while (debt > 0)
{ time <- time + period
debt <- debt*(1 + r*period) - repayments }
Output
cat('Loan will be repaid in', time, 'years\n')
Hasil :

3.5 Vector-based programming


Scripts :
n <- 100
S <- 0
for (i in 1:n)
{ S <- S + i^2 }
S
sum((1:n)^2)
x <- c(-2, -1, 1, 2)
ifelse(x > 0, "Positive", "Negative")
pmin(c(1,2,3),c(3,2,1),c(2,2,2))

Hasil :
3.6 Program flow
Scripts :
x <- 3
for (i in 1:3)
{ show(x)
if (x %% 2 == 0)
{ x <- x/2 }
else
{ x <- 3*x + 1}}
show(x)

Hasil :

3.7 Basic debugging


Scripts :
x <- 3
for (i in 1:3)
{ show(x)
cat("i = ", i, "\n")
if (x %% 2 == 0)
{ x <- x/2 }
else
{ x <- 3*x + 1 }}
show(x)
Hasil :
BAB IV
I/O : INPUT DAN OUTPUT
4.1 Text
Scripts :
# input
x <- 7
n <- 5
# display powers
cat("Powers of", x, "\n")
cat("exponent result\n\n")
result <- 1
for (i in 1:n) {
result <- result * x
cat(format(i, width = 8),
format(result, width = 10),
"\n", sep = "")
}
Hasil :

4.2 Input From a file


4.2.1 Example: file input quartiles1.r
Scripts :
Data1.R
8931207456
Laporan.R

rm(list=ls())
data1= "C:/Users/ACER/Downloads/Metnum/data1.r"
data <- scan(file = data1)
n <- length(data)
data.sort <- sort(data)
data.1qrt <- data.sort[ceiling(n/4)]
data.med <- data.sort[ceiling(n/2)]
data.3qrt <- data.sort[ceiling(3*n/4)]
cat("1st Quartile:", data.1qrt, "\n")
cat("Median: ", data.med, "\n")
cat("3rd Quartile:", data.3qrt, "\n")
Hasil :

Scripts :
quantile(scan("C:/Users/ACER/Downloads/Metnum/data1.r"), (0:4)/4)
Hasil :
4.3 Input from the keyboard
Scripts :
rm(list=ls())
cat("find the zeros of a2*x^2 + a1*x + a0 = 0\n")
a2 <- as.numeric(readline("a2 = "))
a1 <- as.numeric(readline("a1 = "))
a0 <- as.numeric(readline("a0 = "))
discrim <- a1^2 - 4*a2*a0
if (discrim > 0) {
roots <- (-a1 + c(1,-1) * sqrt(a1^2 - 4*a2*a0))/(2*a2)
} else {
if (discrim == 0) {
roots <- -a1/(2*a2)
} else {
roots <- c()
}
}

if (length(roots) == 0) {
cat("no roots\n")
} else if (length(roots) == 1) {
cat("single root at", roots, "\n")
} else {
cat("roots at", roots[1], "and", roots[2], "\n")
}
source("quad2b.R")
Hasil :

4.4 Output to a file


Scripts :
(x <- matrix(1:24, nrow = 4, ncol = 6))
Hasil :

4.5 Plotting
Scripts :

x <- seq(0, 5, by = 0.01)


y.upper <- 2*sqrt(x)
y.lower <- -2*sqrt(x)
y.max <- max(y.upper)
y.min <- min(y.lower)
plot(c(-2, 5), c(y.min, y.max), type = "n", xlab = "x", ylab = "y")
lines(x, y.upper)
lines(x, y.lower)
abline(v=-1)
points(1, 0)
text(1, 0, "focus (1, 0)", pos=4)
text(-1, y.min, "directrix x = -1", pos = 4)
title("The parabola y^2 = 4*x")

Hasil :

Scripts :

par(mfrow = c(2, 2), mar=c(5, 4, 2, 1))


curve(x*sin(x), from = 0, to = 100, n = 1001)
curve(x*sin(x), from = 0, to = 10, n = 1001)
curve(x*sin(x), from = 0, to = 1, n = 1001)
curve(x*sin(x), from = 0, to = 0.1, n = 1001)
par(mfrow = c(1, 1))

Hasil :
BAB V
PROGRAMMING WITH FUNCTIONS

5.1 Functions
5.1.1 Example: roots of a quadratic 3 quad3.r
Scripts :
# program spuRs/resources/scripts/quad3.r
quad3 <- function(a0, a1, a2) {
# find the zeros of a2*x^2 + a1*x + a0 = 0
if (a2 == 0 && a1 == 0 && a0 == 0) {
roots <- NA
} else if (a2 == 0 && a1 == 0) {
roots <- NULL
} else if (a2 == 0) {
roots <- -a0/a1
} else {
# calculate the discriminant
discrim <- a1^2 - 4*a2*a0
# calculate the roots depending on the value of the discriminant
if (discrim > 0) {
roots <- (-a1 + c(1,-1) * sqrt(a1^2 - 4*a2*a0))/(2*a2)
} else if (discrim == 0) {
roots <- -a1/(2*a2)
} else {
roots <- NULL
}
}
return(roots)
}
quad3(1,0,-1)
quad3(1,-2,1)
quad3(1,1,1)

Hasil :
5.1.2 Example: n choose r n_choose_r.r
Scripts :
# program spuRs/resources/scripts/n_choose_r.r
n_factorial <- function(n) {
# Calculate n factorial
n_fact <- prod(1:n)
return(n_fact)
}
n_choose_r <- function(n, r) {
# Calculate n choose r
n_ch_r <- n_factorial(n)/n_factorial(r)/n_factorial(n-r)
return(n_ch_r)
}
n_choose_r(4,2)
n_choose_r(6,4)

Hasil :
5.1.3 Example: Winsorised mean wmean.r
Scripts :
# program spuRs/resources/scripts/wmean.r
wmean <- function(x, k) {
# calculate the k-th Windsorised mean of the vector x
x <- c( 8.244, 51.421, 39.020, 90.574, 44.697,
+ 83.600, 73.760, 81.106, 38.811, 68.517)
n <- length(x)
x[1:k] <- x[k+1]
x[(n-k+1):n] <- x[n-k]
return(mean(x))
}
mean(x)
wmean(x, 2)
x.err <- x
x.err[1] <- 1000
mean(x.err)
wmean(x.err, 2)
Hasil :
5.1.4 Program flow using functions

Scripts :
# swap.r
swap <- function(x) {
# swap values of x[1] and x[2]
y <- x[2]
x[2] <- x[1]
x[1] <- y
return(x)
}
x <- c(7, 8, 9)
x[1:2] <- swap(x[1:2])
x[2:3] <- swap(x[2:3])

Hasil :
5.2 SCOPE AND ITS CONSEQUENCES

Scripts :
test <- function(x) {
y <- x + 1
return(y)
}
test(1)
x
y
y <- 10
test(1)
y
test2 <- function(x) {
y <- x + z
return(y)
}
z <- 1
test2(1)
z <- 2
test2(1)
Hasil :

5.3 ARGUMENTS

Scripts :

formals(test2)
test3 <- function(x = 1) {
return(x)
}
test3(2)
test3()
funk <- function(vibe = c("Do","Be","Dooby","Dooo")) {
vibe <- match.arg(vibe)
return(vibe)
}
funk()
funk("Dooby")
funk("Dum")
Hasil :

Scripts :
test4 <- function(x, ...) {
return(sd(x, ...))
}
test4(1:3)
test4(c(1:2,NA))
test4(c(1:2,NA), na.rm = TRUE)
test4(c(1:2,NA), TRUE)
Hasil :
Scripts :
test5 <- function(x = 1, y = 1, z = 1) {
return(x * 100 + y * 10 + z)
}
test5(2, 2)
test5(y = 2, z = 2)
test6 <- function(a = 1, b.c.d = 1) {
return(a + b.c.d)
}
test6()
test6(b = 5)

Hasil :

5.4 VECTOR-BASED PROGRAMMING USING FUNCTIONS


5.4.1 Example: density of primes primedensity.r
Scripts :
prime <- function(n) {
# returns TRUE if n is prime
# assumes n is a positive integer
if (n == 1) {
is.prime <- FALSE
} else if (n == 2) {
is.prime <- TRUE
} else {
is.prime <- TRUE
for (m in 2:(n/2)) {
if (n %% m == 0) is.prime <- FALSE
}
}
return(is.prime)
}
# input
# we consider primes <= n
n <- 1000
# calculate the number of primes <= m for m in 2:n
# num.primes[i] == number of primes <= i+1
m.vec <- 2:n
primes <- sapply(m.vec, prime)
num.primes <- cumsum(primes)
# output
# plot the actual prime density against the theoretical limit
par(mfrow = c(1, 2), las = 1)
plot(m.vec, num.primes/m.vec, type = "l",
main = "prime density", xlab = "n", ylab = "")
lines(m.vec, 1/log(m.vec), col = "red")
plot(m.vec, num.primes/m.vec*log(m.vec), type = "l",
main = "prime density * log(n)", xlab = "n", ylab = "")
Hasil :

Scripts :
# program spuRs/resources/scripts/prime.r
prime <- function(n) {
# returns TRUE if n is prime
# assumes n is a positive integer
if (n == 1) {
is.prime <- FALSE
} else if (n == 2) {
is.prime <- TRUE
} else {
is.prime <- TRUE
m <- 2
m.max <- sqrt(n) # only want to calculate this once
while (is.prime && m <= m.max) {
if (n %% m == 0) is.prime <- FALSE
m <- m + 1
}
}
return(is.prime)
}
Hasil :

5.5 RECURSIVE PROGRAMMING


5.5.1 Example: n factorial 2 nfact2.r
Scripts :
function nfact2.r
nfact2 <- function(n) {
# calculate n factorial
if (n == 1) {
cat("called nfact2(1)\n")
return(1)
} else {
cat("called nfact2(", n, ")\n", sep = "")
return(n*nfact2(n-1))
}
}
nfact2(6)
Hasil :

5.5.2 Example: Sieve of Eratosthenes primesieve.r


Scripts :
# program spuRs/resources/scripts/primesieve.r
# loadable spuRs function
primesieve <- function(sieved, unsieved) {
# finds primes using the Sieve of Eratosthenes
# sieved: sorted vector of sieved numbers
# unsieved: sorted vector of unsieved numbers
# cat("sieved", sieved, "\n")
# cat("unsieved", unsieved, "\n")
p <- unsieved[1]
n <- unsieved[length(unsieved)]
if (p^2 > n) {
return(c(sieved, unsieved))
} else {
unsieved <- unsieved[unsieved %% p != 0]
sieved <- c(sieved, p)
return(primesieve(sieved, unsieved))
}
}
primesieve(c(), 2:200)
Hasil :

5.6 DEBUGGING FUNCTIONS


Scripts :
my_fun <- function(x) {
browser()
y <- x * z
return(y)
}
my_fun(c(1,2,3))
Called from: my_fun(c(1,2,3))
Browse[1]>
Hasil :

You might also like