我想构建一个调用回归方程(一个lm()
对象)的函数,该函数包含一个循环,该循环返回由索引引用的层的估计值。例如:
frame <- data.frame(y2 = rnorm(100), y = rnorm(100), x = rnorm(100),
strat1 = sample(c(0,1), 100, replace = TRUE),
strat2 = sample(c(1,2,3), 100, replace = TRUE))
effects_table <- matrix(NA, ncol =3, nrow =6)
mat <- matrix(NA, ncol = 3, nrow = 3)
for(j in 0:1) {
for(i in 1:3) {
mod <- lm(y2 ~ x, data = subset(frame, strat1 == j & strat2 == i))
mat[,i] <- c(summary(mod)$coefficients[2,1],
summary(mod)$coefficients[2,2],
summary(mod)$coefficients[2,4])
}
effects_table[((j+1)*(j+1)):(j*3+3),] <- round(mat, 3)
}
最终,我想将其扩展为一个函数,以便我可以调用不同的方程式;类似于以下结构(函数不起作用):
est_stratum <- function(lm_obj) {
effects_table <- matrix(NA, ncol =3, nrow =6)
mat <- matrix(NA, ncol = 3, nrow = 3)
for(j in 0:1) {
for(i in 1:3) {
mod <- lm_obj
mat[,i] <- c(summary(mod)$coefficients[2,1],
summary(mod)$coefficients[2,2],
summary(mod)$coefficients[2,4])
}
effects_table[((j+1)*(j+1)):(j*3+3),] <- round(mat, 3)
}
return(list(effects_table = effects_table))
}
est_stratum(lm(y2 ~ x, data = subset(frame, strat1 == j & strat2 == i))
est_stratum(lm(y ~ x, data = subset(frame, strat1 == j & strat2 == i))
关于如何调用方程并适当考虑循环的任何想法都会很棒。感谢
答案 0 :(得分:1)
以下是我如何处理这个问题,这也有助于消除初始化mat
和effects_table
的麻烦。
f <- function(model, data) {
sapply(split(frame, list(data$strat1, data$strat2)), function(d) {
round(coef(summary(lm(model, d)))[2, -3], 3)
})
}
f(y2~x, frame)
# 0.1 1.1 0.2 1.2 0.3 1.3
# Estimate 0.501 0.034 -0.053 0.006 -0.158 0.057
# Std. Error 0.214 0.358 0.356 0.195 0.378 0.222
# Pr(>|t|) 0.030 0.924 0.884 0.975 0.690 0.800
f(y~x, frame)
# 0.1 1.1 0.2 1.2 0.3 1.3
# Estimate 0.066 -0.318 -0.115 0.133 -0.066 -0.159
# Std. Error 0.191 0.345 0.289 0.232 0.475 0.132
# Pr(>|t|) 0.731 0.369 0.695 0.575 0.894 0.250