title: Determining the order of polynomial regression
body: <p>Let assume that you have 
  <a href="https://i.stack.imgur.com/B4spk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B4spk.png" alt="enter image description here"></a></p>
  
  <p>I am trying to write an algorithm to select a large M such that m &lt; M. Then I would fit the model with m=M. Then if it happens that we reject the t test on the parameter Beta_{m}. Then, it stops and state that m is the degree; else, we set m=m-1 and continue until we stop. </p>
  
  <pre><code>set.seed(1234)
  x &lt;- rnorm(100,0,1)
  y &lt;- x + rnorm(100,x+0.5,0.5)
  dat &lt;- data.frame(cbind(x,y))
  
  func &lt;- function(dat,M) {
    dat &lt;- as.matrix(dat)
    p_value &lt;- list()
    if(length(dat[,1])&gt;M){
      M=M-1
     break
    }
    for (i in 1:M) {
      model &lt;- lm(dat[,1] ~ poly(dat[,-1],i,raw=TRUE))
      p_value[[i]] &lt;- summary(model)$coefficients[i+1, 4]
      if (p_value[[i]]&gt;0.05) {
        break
      } else {
        i=i+1
      }
      p_value1 = do.call(rbind, p_value)
    }
    return(c(p_value1,i-1))
  }
  
  func(dat,200)
  # Error in func(dat, 200) : object 'p_value1' not found 
  </code></pre>
  
  <p>However, with the code above I am not getting what I want with some errors. I was wondering if someone would help me out.</p>
  
  <p><strong>Update</strong>: when I run the code above I have gotten </p>
  
  <pre><code>&gt; func(dat,200)
  [1] 9.255452e-61 1.000000e+00
  </code></pre>
  
  <p>However, how to really account for "select a large M such that m &lt; M" and how to show "m=m-1" every iteration. I meant how can I print out the coefficients each iteration and stop whenever the coefficient is not significant and show all the previous coefficient which are significant. </p>