R Programming

posted in: Term Paper Writing Service | 0


  1. Write a function named tp420 in R that plots a given vector of data as a time series. Your code should take as input a vector x of data and output a plot of x versus time t.Time t should range from 1 to the length of the vector x.
  2. Write a function named fd420 that performs the“first-difference”operation on a given vector x. Your code should take as input a vector x of data and output a vector of first-differences computed from x. Your function should also plot (using tp420) the returned vector as a time series.

Recall that the ith first-difference is the difference between the (i+ 1)th andthe ith elements of x. Check to make sure that the returned vector has length thatis onesmallerthanthelengthofx.

  1. Writeafunctionnamedsacf420thatcalculatesthesampleautocorrelationfunction fromagivenvectorx.Yourcodeshouldtakeasinputavectorxofdataandoutput avectorofsampleautocorrelationscomputedfromx.Yourfunctionshouldalso plot(usingtp420)thereturnedvectorasatimeseries.

Recall that the i-lag sample autocorrelation


ρˆ(i)=γˆ(0)            i=1,2,…,n−1



functioninR.Checktomakesurethatallreturnedcorrelationsarelessthan1in absolutevalue.

  1. Write a function named arpcoeff420 that estimates and returns the parametersfor an AR(p) model. Your code will take as input a vector x of data and a positive integerp,andreturnparametersfittedfromanAR(p)model.

Recall the AR(p)model:

Ytµ+ φ1Yt1+ φ2Yt2+ + φpYtp+st.                                      (1) Your code should return a vector containing estimates of the (p +2) parameters

µ, φ1, φ2, . . . ,φp, σ2.

The parameters φ1, φ2, . . . ,φpcan be estimated by fitting data to the model

Yt=µ+φ1Yt1+φ2Yt2++φpYtp+st                              (2)

treatingitasanordinarylinearregressionmodel.Accordingly,yourcodeshould have the followingsteps.



  • Form the “data” matrix D for the linear regression in (2). If the length of the original data vector x is n, then the data matrix D will have n p rows and p + 1 columns. Looking at (2), we see that the first column of D will bea column of 1s. The second column will have the data xp, xp+1, . . . , xn1. Likewise,thethirdcolumnofDwillhavethedataxp1,xp,…,xn2andthe last (or p + 1th) column of D will have the data x1, x2, . . . ,xnp.
  • FormthedependentvariablevectorYforthelinearregressionin(2).Again looking at (2), we see that Y should be a (n p)-vector containing thedata xp+1,xp+2,…,xn.
  • PerformlinearregressionwithdatamatrixDanddependentvariableY.

Recallthatthecoefficientsofsuchalinearregressionaregivenby (µ,φˆ1,,φˆ2,…,φˆp)T=(DTD)1DTY.

(In R, the solution z to the linear equation Az = b can be obtained using “solve(A,b).” Also, in R, the transpose of a matrix M is obtained as t(M ) and the product of two matrices M and N is obtained as M % ∗%N .)

  • Check to make sure that the solution you give has p + 1 elements. Now estimate σ2from theresiduals.



Last Updated on March 3, 2019 by EssayPro