Stata中如何生成命名为d+原变量名的滞后差分项变量?
Stata: Generate Difference Variables Without Overwriting Original Data
To achieve your goal—creating new difference variables prefixed with d instead of overwriting the original numeric variables—you just need to adjust the variable name in the gen command within your loop. Here's the modified code:
// Get all numeric variables in the dataset ds, has(type numeric) // Loop through each numeric variable and create a new difference variable foreach var in `r(varlist)' { gen d`var' = `var' - `var'[_n-1] }
Key Details:
- The
ds, has(type numeric)command still collects all numeric variables into the macror(varlist), just like your original code. - In the loop,
dvar'constructs the new variable name by prependingdto the original variable name (e.g., if the original variable isincome, the new one becomesdincome`). - The first observation of each new
dvar'variable will be missing (.), since there’s no prior observation (_n-1` doesn’t exist for the first row)—this is normal behavior for this kind of difference calculation.
Important Note:
- Ensure your dataset is sorted correctly before running this code. The
_n-1reference depends on the current row order. For time-series or panel data, sort by the relevant identifier and time variable first (e.g.,sort id year) to guarantee the difference is computed across consecutive observations as intended.
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

