You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Stata中完成多维度数据重塑?解决reshape报错与格式转换问题

Solution for Reshaping Your Stata Dataset

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 12:39:08