title: calling objects in nested function R
body: <p>First off, I'm an R beginner taking an R programming course at the moment. It is extremely lacking in teaching the fundamentals of R so I'm trying to learn myself via you wonderful contributors on Stack Overflow. I'm trying to figure out how nested functions work, which means I also need to learn about how lexical scoping works. I've got a function that computes the complete cases in multiple CSV files and spits out a nice table right now. </p>
  
  <ul>
  <li>Here's the CSV files:
  <a href="https://d396qusza40orc.cloudfront.net/rprog%2Fdata%2Fspecdata.zip" rel="nofollow noreferrer">https://d396qusza40orc.cloudfront.net/rprog%2Fdata%2Fspecdata.zip</a></li>
  <li><p>And here's my code, I realize it'd be cleaner if I used the <code>apply</code> stuff but it works as is:   </p>
  
  <pre><code>complete&lt;- function(directory, id = 1:332){
      data &lt;- NULL
      for (i in 1:length(id)) {
        data[[i]]&lt;- c(paste(directory, "/", formatC(id[i], width=3, flag=0), 
                            ".csv", sep=""))     
      }
      cases &lt;- NULL
  
      for (d in 1:length(data)) { 
        cases[[d]]&lt;-c(read.csv(data[d]))
      }
      df &lt;- NULL
      for (c in 1:length(cases)){
        df[[c]] &lt;- (data.frame(cases[c]))
      }
      dt &lt;- do.call(rbind, df)
      ok &lt;- (complete.cases(dt))
      finally &lt;- as.data.frame(table(dt[ok, "ID"]), colnames=c("id", "nobs"))
      colnames(finally) &lt;- c('id', 'nobs')
      return(finally)
  }
  </code></pre></li>
  </ul>
  
  <p>I am now trying to call the different variables in the dataframe <code>finally</code> that is the output of the above function within this new function:</p>
  
  <pre><code>corr&lt;-function(directory, threshold = 0){
      complete(directory, id = 1:332)
      finally$nobs
  }
  corr('specdata')
  </code></pre>
  
  <p>Without <code>finally$nobs</code> this function spits out the data frame, as it should, but when I try to call the variable <code>nobs</code> in object <code>finally</code>, it says object <code>finally</code> is not found. I realize this problem is due to my lack of understanding in the subject of lexical scoping, my professor hasn't really made lexical scoping very clear so I'm not totally sure how to find the object within the nested function environment... any help would be great.</p>