Announcement

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

  • Splitting a variable by fixed length

    Dear All,

    I am dealing with a variable without any space or delimiters which I need to split. I tried the following commands: split and moss without any success, I tried searching the list-serve without much success The variable I am dealing with has values something like this : 2XMAPHB, 3XTEDK1 and so forth, and the values vary a lot and switches between text and numbers. I will like to split the variable by fixed length if at all possible- like the first 2 letter/number of the variable, then the next 3 and the last 2.

    Another alternative is splitting the values by each letter/number then use concatenate to stitch as necessary.

    I can split the variable in excel, but it is not an ideal situation as I am dealing with hundreds of files.

    Please let me know what I am missing - and will really appreciate the input. Thanks

    Rick


  • #2
    Do you mean
    Code:
    gen newvar1 = substr(original_var, 1, 2)
    gen newvar2 = substr(original_var, 3, 3)
    gen newvar3 = substr(original_var, 6, 2)

    Comment


    • #3
      split requires delimiters, more generally parse strings. split is an officlal command, but previously written by me. I did toy with adding syntax for this case, but that seemed mostly to make it more complicated, while the kind of syntax used by Clyde was already a standard solution and easy to use, if a little tedious.

      We can't comment on your use of moss (SSC), as you don't say exactly what you tried, but Clyde's approach is better here for the fixed lengths you ask for.

      Comment


      • #4
        Thank you Clyde. Your approach worked. I did not even know substr command existed. Thank you again very much

        Comment


        • #5
          substr() is a function, not a command. The distinction is important not just as a matter of terminology but because the rules for functions are different and the documentation for functions is quite separate.

          Comment

          Working...
          X