Writing functions in RStudio

Write two R functions that together will enable you to calculate the maximum likelihood estimates of μ and σ2 on the basis of an iid sample x1, …, xn from a truncated normal distribution with parameters μ, σ2 and τ, where the value of τ is known.

Your first function should be called trnorm.negll(), and should calculate the negative log-likelihood ℓ(μ,σ2;x). The arguments to this function should be (in this order): theta, a vector of length 2 such that theta[1] is the value of μ and theta[2] is the value of σ2; xbar, the sample mean x¯¯¯; SS, the sum of squares ∑ni=1x2i; n, the number of observations; and tau, the value of τ. Note that SS is in UPPER CASE (this is not clear on some browsers); the remaining arguments are in lower case. The value of the function should be the negative log-likelihood −ℓ(μ,σ2;x) (i.e. the expression given in the ‘Introduction’ above, with the minus signs reversed). Your function should return a very large positive value for the negative log-likelihood (corresponding to a very small likelihood) if σ2 is negative.

Your second function should be called trnorm.MLE() and should calculate the maximum likelihood estimates of μ and σ2 given a vector of observations x1, …, xn and a value of τ. The arguments to this function should be: x, the vector of observations; tau, the value of τ; and theta0, a vector of length 2 such that theta0[1] is an initial guess at the value of μ and theta0[2] is an initial guess at the value of σ2. The structure of this function should be as follows:

Calculate the sample mean and sum of squares of the observation vector x.
Call nlm() to minimise the negative log-likelihood as defined in your trnorm.negll() function, starting from the initial value theta0.
Extract the estimated MLE from the result of your nlm() call.
Your trnorm.MLE() function should return a vector of length 2, where the first component is the MLE of μ and the second component is the MLE of σ2.

There is a screenshot below of more details of the question, and a screenshot of how to produce the r file that needs submitting.

Last Completed Projects

topic title academic level Writer delivered