Reputation: 143
I'm trying to implement this model below:
However my code for it is quite messy due to all the Zs and Us, I'm looking for some coding tips to make my code as short and simple as possible?
model = function(N,t1,t2){
Z1 = rnorm(N,0,1)
Z2 = rnorm(N,0,1)
Z3 = rnorm(N,0,1)
Z4 = rnorm(N,0,1)
U1 = runif(N,0,1)
U2 = runif(N,0,1)
T = (U2+t2*U1)/(1+t2)
X1 = (Z1+t1*U1)/(1+t1)
X2= (Z2+t1*U1)/(1+t1)
X3= (Z3+t1*U1)/(1+t1)
X4= (Z4+t1*U1)/(1+t1)
eps = rnorm(100,0,1)
Y = 2*X1 + 3*T*X2 + X3*(T+1)^2+ 4*X4*sin(2*pi*T)/(2-2*sin(2*pi*T))+eps
X = cbind(X1,X2,X3,X4)
return(list(X = X, Y = Y))}
Upvotes: 1
Views: 53
Reputation: 102181
Maybe the code below simplifies a bit
model = function(N,t1,t2){
Z <- matrix(rnorm(4*N),nrow = N)
U <- matrix(runif(2*N),nrow = N)
W <- tcrossprod(U, rbind(c(t2, 1))) / (1+t2)
X <- (Z + t1*U[,1])/(1+t1)
eps <- rnorm(N)
M <- cbind(2,3*W,(W+1)**2,4*sin(2*pi*W)/(2-sin(2*pi*W)))
Y <- M*X + eps
return(list(X = X, Y = Y))
}
Upvotes: 2