complete .R function for coursera course