Announcement

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

  • Pivot to Long data from wide data

    Hi all

    I have a quick query, I have a small dataset that I am trying to switch from wide data to long data. Most of the variables have the time frame in front of them. Others do not have a time frame in front of them. I am trying to switch my data(Dataset is called "AllDatax")


    I have attached a snapshot of the data in an STATA format.


    I am trying to change it to Long format. As you can see most of the variables have a "v" in front of the variable names. This v corresponds to Time. So v0bmi is the BMI at Time 0. v3wototr is the
    wototr at Time 3.


    Essentially I want the long format where there is a time variable column as a snapshot example:

    id otherid sex age race v bmi Comorbidity_Score Depression wototr
    1 1 0 56 1 0 27 0 0 0
    56 1 1
    56 1 2
    2 2 1 79 1 0 28 1 0 21
    2 2 1 79 1 1



    I cannot seem to find a code that will allow me to switch all the variables into a long format and I think the reason I keep getting
    an error is that some of the variables have a v in front of them and the others do not.

    I have tried the following code but it is not giving me the output columns and time columns that I want.

    reshape long v0 v1 v2 v3 v4 v5, i(id otherid) j(v) string

    Would be incredibly grateful for some advice on this.

    Best wishes
    Attached Files
    Last edited by James Lancaster; 09 Aug 2021, 19:45.

  • #2
    Hi James,
    the reason you have not received replies is that you have not followed the forum FAQs on how to share data.
    What you want here for reshape to work is rename the variables and move the time prefixes to suffixes.
    I am assuming you have three variables: bmi, morb and depr - change these accordingly, and 5 periods - extend as needed.
    Note that if you rename them with only the number after the stub, you do not need the string option in reshape.
    Code:
    local vars bmi morb depr
    foreach var of local vars {
    forv i = 1/5 {
    local old_var v`i'`var'
    local new_var `var'`i'
    rename `old_var' `new_var'
    }
    }

    Comment

    Working...
    X