I spent a Sunday on this code to answer some questions for a Coursera course. At this time this code is the norm in more than one such course. So I am just building muscle memory. I type this code and look at the result and learn what I learnt earlier.
If I don't remember how to solve it I search but the point is that I have to be constantly in touch with "R" as well the fundamentals. My day job doesn't let me do this. The other option is a book on Machine Learning like the one by Tom Mitchell but that takes foreover.