title: Function within Function in R
body: <p>Can you please explain to me why the code complains saying that <code>Samdat</code> is not found?</p>
  
  <p>I am trying to switch between models, so I declared a function that contains these specific models and I just need to call this function as one of the argument in the <code>get.f</code> function where the resampling will change the structure for each design matrix in the model. The code complains that <code>Samdat</code> is not found when it is found.</p>
  
  <p>Also, is there a way I can make the conditional statement <code>if(Model == M1())</code> instead of having to create another argument <code>M</code> to set <code>if(M==1)</code>?</p>
  
  <p>Here is my code:</p>
  
  <pre><code>dat &lt;-  cbind(Y=rnorm(20),rnorm(20),runif(20),rexp(20),rnorm(20),runif(20), rexp(20),rnorm(20),runif(20),rexp(20))
  nam &lt;- paste("v",1:9,sep="")
  colnames(dat) &lt;- c("Y",nam)
  
  M1 &lt;- function(){
      a1 = cbind(Samdat[,c(2:5,7,9)])
      b1 = cbind(Samdat[,c(2:4,6,8,7)])
      c1 = b1+a1
      list(a1=a1,b1=b1,c1=c1)}
  
  M2 &lt;- function(){
      a1= cbind(Samdat[,c(2:5,7,9)])+2
      b1= cbind(Samdat[,c(2:4,6,8,7)])+2
      c1 = a1+b1
      list(a1=a1,b1=b1,c1=c1)}
  
  M3 &lt;- function(){
      a1= cbind(Samdat[,c(2:5,7,9)])+8
      b1= cbind(Samdat[,c(2:4,6,8,7)])+8
      c1 = a1+b1
      list(a1=a1,b1=b1,c1=c1)}
  #################################################################
  get.f &lt;- function(asim,Model,M){
      sse &lt;-c()
      for(i in 1:asim){
          set.seed(i)
          Samdat &lt;- dat[sample(1:nrow(dat),nrow(dat),replace=T),]
          Y &lt;- Samdat[,1]
          if(M==1){
              a2 &lt;- Model$a1
              b2 &lt;- Model$b1
              c2 &lt;- Model$c1
              s&lt;- a2+b2+c2
              fit &lt;- lm(Y~s)
              cof &lt;- sum(summary(fit)$coef[,1])
              coff &lt;-Model$cof
              sse &lt;-c(sse,coff)
          }
          else if(M==2){
              a2 &lt;- Model$a1
              b2 &lt;- Model$b1
              c2 &lt;- Model$c1
              s&lt;- c2+12
              fit &lt;- lm(Y~s)
              cof &lt;- sum(summary(fit)$coef[,1])
              coff &lt;-Model$cof
              sse &lt;-c(sse,coff)
          }
          else {
              a2 &lt;- Model$a1
              b2 &lt;- Model$b1
              c2 &lt;- Model$c1
              s&lt;- c2+a2
              fit &lt;- lm(Y~s)
              cof &lt;- sum(summary(fit)$coef[,1])
              coff &lt;- Model$cof
              sse &lt;-c(sse,coff)
          }
      }
      return(sse)
  }
  
  get.f(10,Model=M1(),M=1)
  get.f(10,Model=M2(),M=2)
  get.f(10,Model=M3(),M=3)
  </code></pre>