After my last blog post about why I stopped doing research, I thought I'd take a blog post to discuss one of the major reasons I quit the project: a lack of comments. Before starting the project, I thought it was unnecessary unless I was working with others. However, I quickly found that I forgot what my code did after a couple months. The problem was the sheer scale of the project. I was working with five or six different functions, each with their own inputs and requirements. Every time I wrote new code, I found myself writing new functions to accomplish tasks I already had functions for.
for(i in 1:length(seasons)){
if(trim == FALSE){
loop.var <- 1:length(unique(seasons[[i]]))
}else{
loop.var <- 2:(length(unique(seasons[[i]]))-1)#the first and last season are not full seasons, so you may want to exclude them
}
for(s in loop.var){
sea.s<-unique(seasons[[i]])[s]
use.s<-which(seasons[[i]] == sea.s)
goal.s<-goal[-use.s]
clinics.s<-clinic_data[-use.s,]
m.s<-lm(goal.s~clinics.s)
#which coefficients aren't na?
use.coef.s<-as.vector(which(is.na(m.s$coefficients[-1])==FALSE))
#out of sample prediction
pred.out<-m.s$coefficients[1]+rowSums(as.matrix(clinic_data)[use.s, use.coef.s]%*%as.matrix(m.s$coefficients[-1][use.coef.s]))
oos[use.s,i]<-pred.out
#checks for infinity
if(sum(goal[use.s])==0){
R2Out.i <- NA
}else{
R2Out.i<-1-(var(pred.out-goal[use.s])/var(goal[use.s]))
}
R2Out[use.s,i] <- R2Out.i
R2In[-use.s,i] <- summary(m.s)$r.squared
}#end for s
}#end for i
Here's an example of some code that I wrote, with comments delineated by the # marks. The first comment, "the first and last season are not full seasons, so you may want to exclude them" doesn't explain the code effectively, but rather indicates an option. This in itself isn't a problem, but without further commenting, it becomes very difficult for anyone to understand what my code does. The following two comments are much more useful: "#which coefficients aren't na?" and "#out of sample prediction". I shied away from more of these line-by-line explanations because I didn't want to have to include comments on every line of code. However, now I think that the line-by-line commenting is necessary for me to understand my own code. In the future, that's what I will do.
No comments:
Post a Comment