Announcement

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

  • Reshape long

    Dear Statalisters,
    My data is in a wide form with two indicators for time. I want to reshape it to a long format using only one indicator of time. The variables structure is: Timevar1_Timevar2_varname and I want to reshape it to a long form using only Timevar2.
    Since I have many variable I tried using wildcards using the following code, but I keep getting an error:
    Code:
    reshape long t1_w@_* t2_w@_* t3_w@_* , i(id) j(time2)
    The code works when I specified all time1 variables and variable names, like this:
    Code:
     reshape long  t1_w@_ab1 t1_w@_ab2 t1_w@_ab3 t1_w@_ma10 t1_w@_ma11 t1_w@_ma12 t2_w@_ab1 t2_w@_ab2 t2_w@_ab3 t2_w@_ma10 t2_w@_ma11 t2_w@_ma12 t3_w@_ab1 t3_w@_ab2 t3_w@_ab3 t3_w@_ma10 t3_w@_ma11 t3_w@_ma12, i(id) j(time2)
    Is there a shorter way to reshape it without specifying all variables?

    Thank you!

    The wide form
    Code:
    clear
    input long id byte(t1_w2_ab1 t1_w2_ab2 t1_w2_ab3 t1_w8_ma10 t1_w8_ma11 t1_w8_ma12 t2_w2_ab1 t2_w2_ab2 t2_w2_ab3 t2_w2_ma10 t2_w2_ma11 t2_w2_ma12 t2_w8_ma10 t2_w8_ma11 t2_w8_ma12 t3_w2_ab1 t3_w2_ab2 t3_w2_ab3 t3_w8_ma10 t3_w8_ma11 t3_w8_ma12)
      100 1 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 . . 0 0 0
      200 1 1 0 . . . . . . . . . . . . . . . . . .
      300 1 1 1 0 0 0 . . . . . . . . . . . . . . .
      400 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 1 1 0 0 0 0
      500 1 1 1 0 0 0 1 1 1 0 0 0 1 0 0 0 . . 3 3 0
    end
    The desired long form:

    Code:
    clear
    input long id byte(time2 t1_w_ma10 t1_w_ma11 t1_w_ma12 t1_w_ab1 t1_w_ab2 t1_w_ab3 t2_w_ma10 t2_w_ma11 t2_w_ma12 t3_w_ma10 t3_w_ma11 t3_w_ma12 t2_w_ab1 t2_w_ab2 t2_w_ab3 t3_w_ab1 t3_w_ab2 t3_w_ab3)
    100 2 . . . 1 1 0 0 0 0 . . . 1 1 0 0 . .
    100 8 0 0 0 . . . 0 0 0 0 0 0 . . . . . .
    200 2 . . . 1 1 0 . . . . . . . . . . . .
    200 8 . . . . . . . . . . . . . . . . . .
    300 2 . . . 1 1 1 . . . . . . . . . . . .
    300 8 0 0 0 . . . . . . . . . . . . . . .
    400 2 . . . 1 0 0 0 0 1 . . . 1 0 0 1 1 0
    400 8 0 0 0 . . . 0 0 0 0 0 0 . . . . . .
    500 2 . . . 1 1 1 0 0 0 . . . 1 1 1 0 . .
    500 8 0 0 0 . . . 1 0 0 3 3 0 . . . . . .
    end

  • #2
    You need to collect the variable names into a local macro and then extract the stubs from there.
    Code:
    ds *_w*_*
    local stubs `r(varlist)'
    local stubs = ustrregexra(`"`stubs'"', "_w(\d*)_", "_w@_")
    local stubs: list uniq stubs
    
    reshape long `stubs', i(id) j(time2)
    Last edited by Clyde Schechter; 21 Apr 2023, 11:52. Reason: Correct error in code

    Comment


    • #3
      This works like a charm, thank you Clyde!

      Comment

      Working...
      X