R Algorithm implementation