R:使用两个或多个for循环提取回归结果
基于,我创建了以下矩阵和R:使用两个或多个for循环提取回归结果,r,for-loop,R,For Loop,基于,我创建了以下矩阵和for循环,以循环我的df中的所有回归组合: all_lm <-data.frame(matrix(nrow=180, ncol=9)) names(all_lm)=c("col1", "col2", "Estimate", " Std. Error", " z value", " pValue", "2.5%", "97.5%", "r^2") all_lm在R中的大多数时候,如果您被吸引到使用for循环(更不用说嵌套for循环),那么您可能走错了方向 解决问题
for
循环,以循环我的df中的所有回归组合:
all_lm <-data.frame(matrix(nrow=180, ncol=9))
names(all_lm)=c("col1", "col2", "Estimate", " Std. Error", " z value", " pValue", "2.5%", "97.5%", "r^2")
all_lm在R中的大多数时候,如果您被吸引到使用for
循环(更不用说嵌套for循环),那么您可能走错了方向
解决问题的一般方法是使用expand.grid
函数创建所有输入组合,然后使用mapply
对每个输入组合重复回归并返回结果列表,然后使用do.call
将结果列表合并到数据框中
#
one_lm <- function(i, j, k, l) {
form <- formula(paste0(i,"_PC_AB_",k, " ~ ", l))
result <- lm(form, data = schools, subset=Decile==j)
list(
col1 = i,
col2 = j,
estimate = round(coef(summary(result))[2,1],3),
std_err = round(coef(summary(result))[2,2],3),
z_value = round(coef(summary(result))[2,3],3),
p_value = round(coef(summary(result))[2,4],3),
pct_2.5 = round(confint(result)[2,1],2),
pct_97.5 = round(confint(result)[2,2],2),
r_square = round(summary(result)$r.squared, 3)
)
}
您的代码应该如下所示:
i <- c('A','B','C')
j <- 1:10
k <- c('D','E')
l <- c('F','G','H')
params <- expand.grid(i, j, k, l, stringsAsFactors = FALSE)
现在设置一个函数,mapply
将用于params数据帧的每一行
#
one_lm <- function(i, j, k, l) {
form <- formula(paste0(i,"_PC_AB_",k, " ~ ", l))
result <- lm(form, data = schools, subset=Decile==j)
list(
col1 = i,
col2 = j,
estimate = round(coef(summary(result))[2,1],3),
std_err = round(coef(summary(result))[2,2],3),
z_value = round(coef(summary(result))[2,3],3),
p_value = round(coef(summary(result))[2,4],3),
pct_2.5 = round(confint(result)[2,1],2),
pct_97.5 = round(confint(result)[2,2],2),
r_square = round(summary(result)$r.squared, 3)
)
}
然后,您可以使用do.call
和rbind
函数将所有这些列表合并到一个数据帧中
results <- do.call(rbind, result_list)
结果为什么只有一组支架用于四个控制结构?正如我在文章中所述,当用于包Cairo
时,同样的循环配置工作正常。如上所述,我在所有四个控制结构之后尝试了{大括号(末尾有四个),但这也不起作用。问题再次出现在` all_lm[I,1]'中,如上所述。大括号用于子集行和列。它总是[row,column]
。您的I
变量的值是“A”,然后是“B”,然后是“C”所以,当你运行all_lm[i,1]时,这个依赖于i的行all_lm[i,1]@LeroyTyrone大括号与这个错误没有任何关系,我只是说一致地使用它们,加上适当的缩进将使你的代码更具可读性。。。
result_list <- mapply(one_lm, params[,1], params[,2], params[,3], params[,4], SIMPLIFY = FALSE)
results <- do.call(rbind, result_list)