Search code examples
foreachstatagenerate

Create a variable which is the difference with n-1 and is named dvariable


I would like to do something like this:

ds, has(type numeric)
    foreach var in `r(varlist)' {
    gen `var' = `var' - `var'[_n-1]
}

I would like to name the new variable simply d+oldname.

How can I combine these two wishes?


Solution

  • I think what you are looking for is something along the following lines perhaps:

    sysuse auto, clear
    
    ds, has(type numeric)
    
    foreach var in `r(varlist)' {
        quietly generate d`var' = `var' - `var'[_n-1]           
        display ""
        display "`var'"
        display "d`var'"
    }
    

    Which will produce:

    price
    dprice
    
    mpg
    dmpg
    
    rep78
    drep78
    
    headroom
    dheadroom
    
    trunk
    dtrunk
    
    weight
    dweight
    
    length
    dlength
    
    turn
    dturn
    
    displacement
    ddisplacement
    
    gear_ratio
    dgear_ratio
    
    foreign
    dforeign