R codes - Algorithms - completed