I am currently trying to create a simulation using three different vector for ph
ID: 3110898 • Letter: I
Question
I am currently trying to create a simulation using three different vector for phi, alpha, and beta.
The following is the code I have thus far in R:
As you can see by my function, I am trying to print out the values of phihatbar, g1bar, and gamma. Instead of using for loops, I am trying to use the function sapply() for my simulation calculations.
If I fixed both beta and phi, I can calculate the values with the alpha vector with the following line of code:
But how can I print the values of phihatbar, g1bar, and gamma, by having alpha, phi, and beta to be vectors? I have tried to use the sapply function again, but I am receiving an error.
I am currently trying to create a simulation using three different vector for phi, alpha, and beta.
The following is the code I have thus far in R:
install.packages("FAdist") library(FAdist) ## used to calculate a shifted gamma distribution lamada = 1.000163867 phi = seq(0.01,0.21,0.01) power = c(1:8) alpha = 10^power beta = seq(0.004,1,0.002) n = 10 N=n+5 simu = function(n, phi, lamada, alpha, beta){ M = rpois(N,lambda= -beta*log(phi)) g1=0 phihat=0 for(k in 1:100){ x0 = rgamma3(n=1, shape=alpha, scale=beta, thres=lamada) epsil = 0 for(i in 1:N){ if(M[i]!=0){ Yj = rexp(M[i],rate=alpha) Uj = runif(M[i], 0, 1) eta = sum(Yj^Uj) } else{eta=0} epsil[i] = lamada*(1-phi)+eta } x=0 x[1] = phi*x0+epsil[1] #first observation for(i in 2:N){ x[i] = phi*x[i-1]+epsil[i] } x= x[6:N] phihat[k] = acf(x)$acf[2] phihat[k] = (phihat[k]*n+1)/(n-4) g1[k] = (n/((n-1)*(n-2)*var(x)^(3/2)))*sum((x-mean(x))^3) } phihatbar = mean(phihat) g1bar = mean(g1) gamma = 2/sqrt(beta) newlist = list("phihatbar"= phihatbar, "g1bar"=g1bar, "gamma"=gamma) return(newlist) } As you can see by my function, I am trying to print out the values of phihatbar, g1bar, and gamma. Instead of using for loops, I am trying to use the function sapply() for my simulation calculations.
If I fixed both beta and phi, I can calculate the values with the alpha vector with the following line of code:
sapply(alpha, simu, n=n, phi=phi, lamada=lamada, beta=beta)
But how can I print the values of phihatbar, g1bar, and gamma, by having alpha, phi, and beta to be vectors? I have tried to use the sapply function again, but I am receiving an error.
Explanation / Answer
You can use pmap or map2 from the purrr package. This is going to execute a function over a set consisting of lists of equal length that too in parallel. It runs the function with first element of each argument , then second and so on.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.