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.