【问题标题】:How to reshape data multiple ways in Stata?如何在Stata中以多种方式重塑数据?
【发布时间】:2020-01-30 14:34:31
【问题描述】:

我正在处理一个涵盖多个国家、变量和年份的数据集。它目前的组织范围很广(实际上是大约 30 年,每个国家/地区有 5 个不同的变量):

country measure yr1995 yr1996 yr1997
USA A 5 4 1
USA B 1 2 1
USA C 0 4 2
UK A 2 4 9
UK B 2 8 4
UK C 2 4 1

我想要的是像这样重新排列数据:

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

我尝试使用reshape long yr, i(country) j(year),但收到以下错误消息:

variable id does not uniquely identify the observations
    Your data are currently wide.  You are performing a reshape long.  You specified i(country) and j(year).  In
    the current wide form, variable country should uniquely identify the observations.

我认为这是因为country 不是唯一的长变量? (measure也是?)

除了解决这个问题和安排年长而不是宽,我认为这个命令不会完成将不同变量(A、B、C)移动到宽格式作为列标题的其他任务。

我需要为此使用单独的reshape wide 命令吗?或者有什么方法可以扩展命令以同时执行这两项操作?

【问题讨论】:

    标签: stata reshape transpose


    【解决方案1】:

    这是一个双重reshape。至少可以这样做;此外,这似乎很重要,因为年份需要很长,而不是很宽,并且衡量标准需要很宽,而不是很长,所以这两个问题都存在。

    经济发展数据往往是这样来的。事实上,这个问题已经引起了至少一篇专门的短篇论文 in the Stata Journal, but visible to all

    您的数据示例很有帮助,并且几乎立即有用,但请阅读 Stata 标签和 help dataex(如有必要,请先使用 ssc install dataex 安装 dataex)。

    另请参阅this FAQ,其中包括 Stata 帮助和手动输入之外的一些提示。

    Stata 中的search reshape 会指向这些资源。

    clear
    input str3 country str1 measure yr1995 yr1996 yr1997
    USA A 5 4 1
    USA B 1 2 1
    USA C 0 4 2
    UK A 2 4 9
    UK B 2 8 4
    UK C 2 4 1
    end 
    
    reshape long yr, i(country measure) j(year) 
    
    reshape wide yr, i(country year) j(measure) string 
    
    rename (yr*) * 
    
    list, sepby(country)
    
         +----------------------------+
         | country   year   A   B   C |
         |----------------------------|
      1. |      UK   1995   2   2   2 |
      2. |      UK   1996   4   8   4 |
      3. |      UK   1997   9   4   1 |
         |----------------------------|
      4. |     USA   1995   5   1   0 |
      5. |     USA   1996   4   2   4 |
      6. |     USA   1997   1   1   2 |
         +----------------------------+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 2015-05-04
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多