Create an R function to calculate factorials. You are not allowed to use the built-in function factorial().
1.function name is
"new"
## [1] "new"
2.Argument is n 3.If function distinglish n>1 or n<1 1When n < 1, return 1. 2When n > 1, return factorials.
new <- function(n){
j <- 1 #j set up 1
save<-NULL
while(j <= length(n)){ #j set up number of n
if(n[j] == 0){ #When n[j] is zero
save<-c(save,1) #save 1. In other words ,n = 1.
}else{A <- 1 #A set up 1
while(n[j] >= 1){ #When n>1,factorial(from 1 to n)
A <- n[j]*A #A reset up 1*n[j]
n[j] <- n[j]-1} #n[j] is number of n-1
save<-c(save,A)}
j <- j+1 #j plus 1, and again(until number of n)
}
return(save) #output n!
}
Using your own factorial function, create an R function to calculate the number of possible combinations that can be obtained by taking a subset of elements from a larger set. 1.function name is
'kf'
## [1] "kf"
kf <- function(n,k) # using former function. Substitute former n,K for function
{return(new(n)/(new(k)*new(n-k)))
}
Using your own combination function, create an R function to calculate the probability mass of binomial distributions. You are not allowed to use the built-in function dbinom().
pf <- function(n,x,p) # using former function.
{return(kf(n,x)*p^x*(1-p)^(n-x))
}
Using your own binomial PMF, display graphically the PMF of binomial dis-ributions for n = 2; 5; 10; and 50.
1.P is 0.5 and 0.3.
#n is 2 and x is 0:2
x <- 0:2
plot(x, pf(2,x,.5))
#n is 5 and x is 0:5
x <- 0:5
plot(x, pf(5,x,.5))
#n is 10 and x is 0:10
x <- 0:10
plot(x,pf(10,x,.5))
#n is 50 and x is 0:50
x <- 0:50
plot(x,pf(50,x,.5))
#n is 2 and x is 0:2
x <- 0:2
plot(x, pf(2,x,.3))
#n is 5 and x is 0:5
x <- 0:5
plot(x, pf(5,x,.3))
#n is 10 and x is 0:10
x <- 0:10
plot(x,pf(10,x,.3))
#n is 50 and x is 0:50
x <- 0:50
plot(x,pf(50,x,.3))
#end