added existing R code, made some changes