detailed R code