Search code examples
robjectnested-functionlexical-scope

calling objects in nested function R


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.

  • Here's the CSV files: https://d396qusza40orc.cloudfront.net/rprog%2Fdata%2Fspecdata.zip
  • And here's my code, I realize it'd be cleaner if I used the apply stuff but it works as is:

    complete<- function(directory, id = 1:332){
        data <- NULL
        for (i in 1:length(id)) {
          data[[i]]<- c(paste(directory, "/", formatC(id[i], width=3, flag=0), 
                              ".csv", sep=""))     
        }
        cases <- NULL
    
        for (d in 1:length(data)) { 
          cases[[d]]<-c(read.csv(data[d]))
        }
        df <- NULL
        for (c in 1:length(cases)){
          df[[c]] <- (data.frame(cases[c]))
        }
        dt <- do.call(rbind, df)
        ok <- (complete.cases(dt))
        finally <- as.data.frame(table(dt[ok, "ID"]), colnames=c("id", "nobs"))
        colnames(finally) <- c('id', 'nobs')
        return(finally)
    }
    

I am now trying to call the different variables in the dataframe finally that is the output of the above function within this new function:

corr<-function(directory, threshold = 0){
    complete(directory, id = 1:332)
    finally$nobs
}
corr('specdata')

Without finally$nobs this function spits out the data frame, as it should, but when I try to call the variable nobs in object finally, it says object finally 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.


Solution

  • The object finally is only in scope within the function complete(). If you want to do something further with the object you are returning, you need to store it in a variable in the environment you are working in (in this instance, the environment you are working in is the function corr(). If we weren't working inside any function, the environment would be the "global environment"). In other words, this code should work:

    corr<-function(directory, threshold=0){
        this.finally <- complete(directory, id=1:332)
        this.finally$nobs
    }
    

    I am calling the object that is returned by complete() this.finally to help distinguish it from the object finally that is now out of scope. Of course, you can call it anything you like!