我不知道为什么这个R循环代码不起作用

时间:2019-09-10 05:36:35

标签: r loops regression

我为两个子组组合和两个因变量进行了线性回归的循环编码。 但这不会出错。 有没有人可以修复我的代码?

each_lm <-data.frame(matrix(nrow=1, ncol=10))
names(each_lm)=c("col1", "col2", "col3", "Estimate", " Std. Error", " z value", " pValue", "2.5%", "97.5%","r^2")
e=1
for (i in c("sbp","dbp")) {
  for (j in c("1","2","3","4","5")) {
   for (k in c("2002","2005","2008","2011","2014","2017")){
      form <- formula(paste0(i,"~bmi"))
      result <- lm(form, data=subset(bp, gr_bmi==j & year==k)
      each_lm[e,1]<-i
      each_lm[e,2]<-j
      each_lm[e,3]<-k
      each_lm[e,4]<-round(coef(summary(result))[2,1],3)
      each_lm[e,5]<-round(coef(summary(result))[2,2],3)
      each_lm[e,6]<-round(coef(summary(result))[2,3],3)
      each_lm[e,7]<-round(coef(summary(result))[2,4],3)
      each_lm[e,8]<-round(confint(result)[2,1],2)
      each_lm[e,9]<-round(confint(result)[2,2],2)
      each_lm[e,10]<-round(summary(result)$r.squared, 3)
    e<-e+1
    }
  }
}
write.xlsx(each_lm, "c:/R/sbp_bmi/Table4_2.xlsx")

错误消息:

Error: unexpected symbol in:
"      result <- lm(form, data=subset(bp, gr_bmi==j & year==k)
      each_lm"
Error: object 'k' not found
Error in round(summary(result)$r.squared, 3) : 
  non-numeric argument to mathematical function
Error: unexpected '}' in "    }"
Error: unexpected '}' in "  }"
Error: unexpected '}' in "}"

1 个答案:

答案 0 :(得分:2)

错误是您的一个功能未正确关闭。在该行中:

result <- lm(form, data=subset(bp, gr_bmi==j & year==k)

只有1个右括号,而应该有2个,因为您要调用2个函数。

用它代替它会解决

result <- lm(form, data=subset(bp, gr_bmi==j & year==k))