title: I don't know why this R loop code doesn't work
body: <p>I made loop code for linear regression by two subgroups combination and for two dependent variable.
  But it doesn't work with error. 
  Is there someone can fix my code?</p>
  
  <pre class="lang-r prettyprint-override"><code>each_lm &lt;-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 &lt;- formula(paste0(i,"~bmi"))
        result &lt;- lm(form, data=subset(bp, gr_bmi==j &amp; year==k)
        each_lm[e,1]&lt;-i
        each_lm[e,2]&lt;-j
        each_lm[e,3]&lt;-k
        each_lm[e,4]&lt;-round(coef(summary(result))[2,1],3)
        each_lm[e,5]&lt;-round(coef(summary(result))[2,2],3)
        each_lm[e,6]&lt;-round(coef(summary(result))[2,3],3)
        each_lm[e,7]&lt;-round(coef(summary(result))[2,4],3)
        each_lm[e,8]&lt;-round(confint(result)[2,1],2)
        each_lm[e,9]&lt;-round(confint(result)[2,2],2)
        each_lm[e,10]&lt;-round(summary(result)$r.squared, 3)
      e&lt;-e+1
      }
    }
  }
  write.xlsx(each_lm, "c:/R/sbp_bmi/Table4_2.xlsx")
  </code></pre>
  
  <p>Error message:</p>
  
  <pre class="lang-none prettyprint-override"><code>Error: unexpected symbol in:
  "      result &lt;- lm(form, data=subset(bp, gr_bmi==j &amp; 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 "}"
  </code></pre>