Dear Statalist,

I need to use _pctile inside another ado that only accepts eclass programs. My original solution was to create a wrapper that takes _pctile rclass results and put them into a matrix. Though that works, in the context of a lot of data and loops, total execution time is over 30h. And I believe this is largely due to the inefficiency of my solution.

With the mock case below, I can see that the wrapper has increased five fold the execution time of the operation. Could any one suggest a better way to handle this?

Any help would be much appreciated!

HTML Code:
cap program drop eclass_pctile
program define eclass_pctile, eclass
  
  * This is a wrapper to make the rclass program _pctile into an eclass
  * Usual outputs are r(r1)... r(rN) -> matrix b = (r(r1), ..., r(rN))
  _pctile `0'
  
  * Interlude to name the columns nicely (varname_p1 ... varname_pN)
  gettoken varname options : 0, parse(" ,")
    
  * Create strings with all elements and all column names
  local elements "`r(r1)'"  
  local colnames "`varname'_r1"
  local i = 2
  while !missing("`r(r`i')'")  {
    local elements "`elements', `r(r`i')'"
    local colnames "`colnames' `varname'_r`i'"
    local ++ i
  }
    
  * Put the string of elements in a 1 line matrix with N columns
  matrix b = (`elements')
  
  * Name the matrix columns
  matrix colnames b = `colnames'

  ereturn post b
  
end

* Test execution time with a mock (my use case has many observations, thus expand)
clear
sysuse auto
expand 1000
set rmsg on

* For a small number of results, the execution time is quite similar
_pctile price, n(10)
eclass_pctile price, n(10)

* For a large number of results, the modified version takes 5x longer
_pctile price, n(500)
eclass_pctile price, n(500)