Announcement

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

  • Ideas on how to convert a hyphenated interval (e.g. '5-8') into its constituent integers delimited by commas (e.g. '5,6,7,8')?

    Hi,
    As my post title states, I have data with varied hyphenated intervals such as '3-6', '1-5', '10-12', and so on, and I want to convert these into their consituent integers delimited by commas. So '3,4,5,6', '1,2,3,4,5', and '10,11,12', respectively. Does anyone have any ideas as to how this could be done?

    Thank you

  • #2
    There are many ways I could envision to do this. I assumed that your data are in the following format, where you have a variable containing these ranges. I'm not certain it's the most efficient way, but it works. Since the number list is built inside a local macro, it will work well as long as your number ranges are not too wide.

    Code:
    clear *
    cls
    
    input str6(have)
    "5-8"
    "1-10"
    "20-30"
    end
    
    split have, p(-)
    rename (have1 have2) (start stop)
    
    gen alist = ""
    forval i = 1/`=_N' {
      qui numlist "`=start[`i']'/`=stop[`i']'"
      qui replace alist = "`=r(numlist)'" if _n==`i'
    }
    replace alist = subinstr(alist, " ", ",", .)
    list
    
         +---------------------------------------------------------+
         |  have   start   stop                              alist |
         |---------------------------------------------------------|
      1. |   5-8       5      8                            5,6,7,8 |
      2. |  1-10       1     10               1,2,3,4,5,6,7,8,9,10 |
      3. | 20-30      20     30   20,21,22,23,24,25,26,27,28,29,30 |
         +---------------------------------------------------------+

    Comment


    • #3
      Thank you Leonardo. Will try it out.

      Comment

      Working...
      X