SQL analytic-like functions in R