This is a homework about how to use R Markdown and write a function by Rstudio.

In question 1,I need to write a factorial function and let it can be used in the next questions.first of all,use ‘if’ function to judge wether n=0,if n=0,the answer will be 1, and if not, it will get into the ‘for loop’.About the ‘for loop’ let s=1 ahead of the ‘for loop’. Than,let i is inclouded in [0,n].And let ’s<-s*i’ ‘s’ will be the save of the calculate. After the loop I will finally get the answer of the factorial. This function will be used in the question2,3,4. But it can only be successful used in question2,3 but can’t get a plot in question 4. So I need to make the function can due with the vector that contain multiple values.So, let ‘s1’ to save the result. Use ‘a’ to be the value contained in the ‘length(n)’. Use this the ‘mf’ can calculate the vector that contain mutiple values.

mf<-function(n)  ## new function about the factorial
{
s1<-NULL ## s1 is be used to save the result,first of all there is no value in it
a<-1
while(a<=length(n)) ## a is the value that contained in the length(n)
{
 if(n[a]==0)
 {
  s1<-c(s1,1) ## when n=0 the answer is 1
  }else ## if n is not equal 0, it will enter in the next loop
 {
  s=1
  for(i in 1:n[a])
  {
  s=s*i ## this 'for loop' shows the factorial function
  }
  s1<-c(s1,s)}
  a<- a+1}
  return(s1)## result of the function
}
mf(0:5) 
## [1]   1   1   2   6  24 120
mf(0) ## test if the function can run success
## [1] 1

In question 2, I just put the ‘mf’ function which I wrote in question 1 into the equation, to get the new function ‘mf2’.

mf2<-function(n,k) ## built a function mf2
{
return(
mf(n)/(mf(k)*mf(n-k))
) ## the result of the function
}
mf2(5,3) ## test if it can run
## [1] 10

In question 3, I put the ‘mf2’ into the equation, to wrote a function ‘f’ that can calculate the probabilty mass of binomial distributions.

f<-function(n,x,p) ## built a function 'f'
{
return(mf2(n,x)*(p^x)*(1-p)^(n-x))
} ## the result of this function
f(5,2,0.5) ## test if it can work
## [1] 0.3125

In question 4, I used the ‘f’ function to draw some graphs about the PMF of binomial distributions when n=2,5,10,50.In this time I used ‘for loop’ to draw them at the same time. I took p=0.6 at the first time and took p=0.3 at the second time.

n<-c(2,5,10,50) ## let n=2,5,10,50
for(i in n) ## this loop is used to draw 4 graphs at the same time
{
x<-0:i
plot(x,f(i,x,0.6)) ## let p=0.6,draw 4 plot graphs
}

n<-c(2,5,10,50)
for(i in n)
{
x<-0:i
plot(x,f(i,x,0.3)) ## this time p=0.3
}

Above all is what I did in this homework.