refacotred R code