[英]How to generate this R function for random effect model?
I'm trying to create a code such that Y = 5g1(X1) + 3g2(X2) + 4g3(X3) + 6g4(X4) + sqrt(1.74)*eps
(the functions g, are defined in the code).我正在尝试创建一个代码,使得Y = 5g1(X1) + 3g2(X2) + 4g3(X3) + 6g4(X4) + sqrt(1.74)*eps
(函数 g,在代码中定义)。
X = (X1,...,Xp)
should be an nxp
dimensional design matrix, however I'm not sure about how to generate that based on this information where Xj = W+U
is simulated according to a random effects model. X = (X1,...,Xp)
应该是一个nxp
维设计矩阵,但是我不确定如何根据这些信息生成它,其中Xj = W+U
是根据随机效应 model 模拟的。 I tried using X = do.call(cbind, replicate(p, X, simplify=FALSE))
but this just replicates each Xj, i'm not sure that's what should be done, they should be different.我尝试使用X = do.call(cbind, replicate(p, X, simplify=FALSE))
但这只是复制每个 Xj,我不确定应该这样做,它们应该不同。
Any advice on what i have missed would be appreciated and any improvements on the code too to make it more concise.任何关于我错过的建议将不胜感激,并且对代码的任何改进也将使其更简洁。
n<- 400
p<- 1000
W = runif(n)
U = runif(n)
eps = rnorm(n)
for (j in 1:p){
X = W+U
X = as.matrix(X)
return(X)} #This is a nx1 matrix...
#alternatively write: X = do.call(cbind, replicate(p, X, simplify=FALSE))
g1 = X
g2 = (2*X-1)^2
g3 = sin(2*pi*X)/(2-sin(2*pi*X))
g4 = 0.1*sin(2*pi*X) + 0.2*cos(2*pi*X) + 0.3*sin(2*pi*X)^2 + 0.4*cos(2*pi*X)^3 + 0.5*sin(2*pi*X)^3
Y = 5*g1 + 3*g2 + 4*g3 + 6*g4 + sqrt(1.74)*eps
return(Y)
}
I am not sure to capture the logic of your calculation, eventually it is something like this:我不确定你的计算逻辑,最终是这样的:
n <- 40 # 400
p <- 100 # 1000
X <- replicate(p, runif(n) + runif(n)) ## W+U
y <- function(X) {
g1 <- X
g2 <- (2*X-1)^2
g3 <- sin(2*pi*X)/(2-sin(2*pi*X))
g4 <- 0.1*sin(2*pi*X) + 0.2*cos(2*pi*X) + 0.3*sin(2*pi*X)^2 + 0.4*cos(2*pi*X)^3 + 0.5*sin(2*pi*X)^3
eps <- rnorm(length(X))
Y <- 5*g1 + 3*g2 + 4*g3 + 6*g4 + sqrt(1.74)*eps
return(Y)
}
Y <- apply(X, 2, FUN=y)
Also the variant without apply()
works:没有apply()
的变体也有效:
Y <- y(X)
To compare both variants:要比较两种变体:
set.seed(42)
Y1 <- apply(X, 2, FUN=y)
set.seed(42)
Y2 <- y(X)
identical(Y1, Y2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.