如何在Stata中完成多维度数据重塑?解决reshape报错与格式转换问题
Hey there! You’re spot-on about why the initial reshape command threw an error—let’s walk through exactly how to transform your data into the desired format, step by step.
Why the Error Happened
Your guess is correct: the i(country) identifier isn’t enough to uniquely label each row in your wide dataset. Each country has 3 separate rows for measures A, B, and C, so you need both country and measure as your unique identifiers for the first reshape step.
Step 1: Reshape Long (Year Columns to Rows)
First, we’ll convert the year columns (yr1995, yr1996, etc.) into a single year variable. Use this command:
reshape long yr, i(country measure) j(year)
After running this, your data will look like this (abbreviated):
country measure year yr
USA A 1995 5
USA A 1996 4
USA A 1997 1
USA B 1995 1
UK A 1995 2
...
Step 2: Reshape Wide (Measures to Columns)
Next, we’ll pivot the measure values (A/B/C) into separate columns, using country and year as the unique identifiers this time:
reshape wide yr, i(country year) j(measure) string
The string option tells Stata that measure is a text-based variable (since A/B/C are string labels). Finally, clean up the column names to remove the yr prefix:
rename yr* *
Combined One-Liner (Optional)
If you want to run both steps in one go, chain the commands with pipes:
reshape long yr, i(country measure) j(year) | reshape wide yr, i(country year) j(measure) string | rename yr* *
Final Result
Your dataset will now match exactly the format you wanted:
country year A B C
USA 1995 5 1 0
USA 1996 4 2 4
USA 1997 1 1 2
UK 1995 2 2 2
UK 1996 4 8 4
UK 1997 9 4 1
内容的提问来源于stack exchange,提问作者Jay

