No the Start and End might be in different years. Then simply adding 1 will not work.
Company Start End
A 2018m12 2019m02
B 2016m12 2017m03
Using stata, from the above I want to make the below data.
Company Month
A 2018m12
A 2019m01
A 2019m02
B 2016m12
B 2017m01
B 2017m02
B 2017m03
ChatGPT's solution is this, but it seems it doesn't use forval correctly, but maybe this provides a hint.
Company Start End
A 2018m12 2019m02
B 2016m12 2017m03
Using stata, from the above I want to make the below data.
Company Month
A 2018m12
A 2019m01
A 2019m02
B 2016m12
B 2017m01
B 2017m02
B 2017m03
Code:
clear input str6 Company Start End "A" "2018m12" "2019m02" "B" "2016m12" "2017m03" end
ChatGPT's solution is this, but it seems it doesn't use forval correctly, but maybe this provides a hint.
Code:
clear * Create your original dataset input str1 Company str7 Start str7 End A 2018m12 2019m02 end * Extract the year and month components from Start and End gen start_year = year(monthly(Start, "Ym")) gen start_month = month(monthly(Start, "Ym")) gen end_year = year(monthly(End, "Ym")) gen end_month = month(monthly(End, "Ym")) * Initialize a counter variable gen counter = 1 * Create an empty dataset to hold the results tempfile expanded_data save "`expanded_data'" * Loop through the years and months, and generate Month variable forval year = start_year(1)end_year { local end_month = 12 if `year' == `end_year' { local end_month = `end_month' } forval month = start_month(1)`end_month' { gen Month = "`year'm0`month'" save "`expanded_data'", append local counter = `counter' + 1 } } * Merge the expanded data with the original dataset to get the Company variable use "`expanded_data'", clear sort Month gen counter = _n sort Company counter drop counter merge 1:1 counter Company using original_dataset drop counter * Display the result list Company Month
Comment