Updated R script (v7)