我想模拟一些数据并返回Beta 1和Beta 2的不同估计值。我想使用复制或类似功能作为lappy,sapply。
beta = matrix(data = rep(NA, 200), ncol = 2)
colnames(beta) = c("Beta 1", "Beta 2")
beta = replicate (100,{
x = matrix(data = rep(NA, 300), ncol = 3)
colnames(x) = c("y", "x1", "x2")
x$y = rnorm(100,2,4)
x$x1 = rnorm(100, 4,6)
x$x2 = rnorm(100, 5,7)
lm = lm(y ~ x1 + x2, data = x)
coef(lm)[2] ; coef(lm)[3]
})
以上仅返回100个重复的一个beta
答案 0 :(得分:2)
beta = replicate (100,{
x = matrix(data = rep(NA, 300), ncol = 3)
colnames(x) = c("y", "x1", "x2")
x = data.frame(y=rnorm(100,2,4),
x1=rnorm(100, 4,6),
x2=rnorm(100, 5,7))
lm = lm(y ~ x1 + x2, data = x)
beta=c(Beta1=coef(lm)[2],Beta2=coef(lm)[3])
})
beta=t(beta)
答案 1 :(得分:0)
使用sapply
:
res <- sapply(1:100, function(i){
x = matrix(data = rep(NA, 300), ncol = 3)
colnames(x) = c("y", "x1", "x2")
x$y = rnorm(100,2,4)
x$x1 = rnorm(100, 4,6)
x$x2 = rnorm(100, 5,7)
lm = lm(y ~ x1 + x2, data = x)
return(c(coef(lm)[2], coef(lm)[3]))
})
head(t(res))
# x1 x2
# [1,] 0.01293551 -0.002520876
# [2,] 0.00294546 -0.034689928
# [3,] 0.05614309 0.049577728
# [4,] -0.02323345 -0.025082705
# [5,] -0.01016728 0.023558755
# [6,] -0.05317357 0.024496896