cal_fact <- function(n) {
#Arugument:n
if(n < 0) { # The case which the argument is less than zero
#Display an error message
y <- c("The argument must be larger than 0.")
return(y) #Return y
}
if(n == 0) { #If x equals to zero
y <- 1
return(y) #Return y
}
if(n > 0) { # If the argument is larger than zero
x <- seq(1,n,by = 1) #integers from 1 to n
y <- prod(1:n) #Multiply from 1 to n
return(y) #Return y
}
}
Compare “cal_fact” with “factorial” in R.
#Comparison between the user defiend function, cal_fact, and factorial in R
cal_fact(4)
## [1] 24
factorial(4)
## [1] 24
Get the same answer.
cal_com <- function(n,k){
# Arguments: n, k
if(n < k) { # If k is larger than n
z <- 0
return(z) #Return z
}
if(n >= k) { #If n is larger than k
s <- cal_fact(n)
r <- (cal_fact(k) * cal_fact(n - k))
z <- s / r
return(z) # Return z
}
}
Compare “cal_com” with “choose” in R.
#Comparison between the user defiend function, cal_com, and choose in R
cal_com(5,3)
## [1] 10
choose(5,3)
## [1] 10
Get the same answer.
cal_bin <- function(x,n,p) {
# Arguments: x - number of success (integer)
# n - number of bernoulli trials (integer)
# p - probability of success (integer)
a <- cal_com(n,x)
b <- p ^ x
c <- (1 - p) ^ (n - x)
d <- a * b * c # Calculate the binomial probability
return(d) #Return d
}
Compare “cal_bin” with “dbinom” in R.
#Comparison between the user defiend function, cal_bin, and dbinom in R
cal_bin(1,10,0.5)
## [1] 0.009765625
dbinom(1,10,0.5)
## [1] 0.009765625
Get the same answer.
Display the plot of “p=0.2”.
op <- par(mfrow=c(2,2)) #Decide the place of graph
for (i in c(2,5,10,50)) { # loop for the simulation, i = 2, 5, 10, 50
chk <- rep(NA, length = i)
for(j in 0:i){ # loop for the simulation, i = 0, 1, ..., i
chk[j + 1] <- cal_bin(j, i, 0.2)
}
barplot(chk, xlab = "Number of Success", ylab = "Probability", col = "gray", main = paste("n=",i))
# Display the plot of "p = 0.2" with dividing by "n"
}
Display the plot of “p=0.4”.
op <- par(mfrow=c(2,2)) #Decide the place of graph
for (i in c(2,5,10,50)) { # loop for the simulation, i = 2, 5, 10, 50
chk <- rep(NA, length = i)
for(j in 0:i){ # loop for the simulation, i = 0, 1, ..., i
chk[j + 1] <- cal_bin(j, i, 0.4)
}
barplot(chk, xlab = "Number of Success", ylab = "Probability", col = "gray", main = paste("n=",i))
# Display the plot of "p = 0.2" with dividing by "n"
}