Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Creating a compound-quote separated list with invtokens()

    Hi Statalist,

    I'm trying to use invtokens() to take a string vector and transform it into a single string. For example
    Code:
    mata invtokens( ("firstelem","secondelem") )
    returns "firstelem secondelem". My problem is when an element in the string vector contains a space.

    Code:
    mata invtokens( ("firstelem","second elem") )
    returns "firstelem second elem" (losing the information about where the second element starts and ends).

    Does anyone know how I could input ("firstelem","second elem") and have it return "`"firstelem"' `"second elem"'"?

    Thank you,

    Andrew Maurer

  • #2
    Use Ben Jann's moremata package, which you can install with ssc install moremata. For example:
    Code:
    . mata mm_invtokens( ("firstelem","second elem") )
      firstelem "second elem"
    
    . mata mm_invtokens(("firstelem","second elem"),noclean=1)
      `"firstelem"' `"second elem"'

    Comment


    • #3
      Thanks Phil, this is exactly what I was looking for.

      In case this is of use to anyone, I wrote a simple program, levelsoflabel, that can, in some cases, be used as a much faster substitute to levelsof. (Any pedantic comments about coding style are most welcome).

      Code:
      *! version 1.0.0 28may2014
      
      // program returns the levels of a value label attached to a variable
      // useful in lieu of levelsof for large datasets, assuming that:
      //  1) there are no unlabeled values of the variable
      //  2) there is at least one observation for each label level
      
      cap program drop levelsoflabel
      program define levelsoflabel, rclass
      syntax varname, [text local(name)]
          
      if "`text'" == "" mata _levelsoflabel("`varlist'",0,"loc")
      else mata _levelsoflabel("`varlist'",1,"loc")
      
      return local levels `"`loc'"'
      if "`local'" != "" c_local `local' `"`loc'"'
      else noi di `"`loc'"'
      
      end
      
      mata
      void _levelsoflabel(string scalar varname, real scalar text, string scalar loc) {
          
          string scalar labname, out
          string vector labtext
          real vector labvals
          
          labname = st_varvaluelabel(varname)
          
          // error check
          if (labname == "") _error("There is no label associated with variable " + varname)
              
          // put levels (text or values) into string scalar out
          st_vlload(labname,labvals,labtext)
          if (!text) out = mm_invtokens(strofreal(labvals))
          else if (text) out = mm_invtokens(labtext,1)
          
          // return local to calling program
          st_local(loc,out)
          
      }
      end

      Comment

      Working...
      X