相当于 Excel 在 Stata 中旋转

Equivalent of Excel Pivoting in Stata

我一直在 Stata 中处理需要重塑的国家级调查数据。我最终将 .dta 导出到 .csv 并在 Excel 中创建了一个枢轴 table 但我很想知道如何在 Stata 中执行此操作,因为我无法弄清楚。

假设我们有以下数据:

country response
A 1
A 1
A 2
A 2
A 1
B 1
B 2
B 2
B 1
B 1
A 2
A 2
A 1

我希望将数据重新格式化为:

country sum_1 sum_2
A 4 4
B 3 2

首先,我尝试了一个简单的 reshape wide 命令,但在意识到 reshape 没有额外步骤的情况下无论如何都无法工作之前,我得到了 "values of variable response not unique within country" 的错误。

然后我尝试根据 response 的值生成新变量,然后尝试使用 reshape...整个事情变得一团糟所以我只使用了 Excel.

只是好奇是否有更直观的方法来进行这种转换。

如果您只想要一个 table,那么只需要一个:

clear 
input str1 country response
A 1
A 1
A 2
A 2
A 1
B 1
B 2
B 2
B 1
B 1
A 2
A 2
A 1
end 

tabulate country response 

           |       response
   country |         1          2 |     Total
-----------+----------------------+----------
         A |         4          4 |         8 
         B |         3          2 |         5 
-----------+----------------------+----------
     Total |         7          6 |        13 

如果你想把数据改成这样,reshape是答案的一部分,但你应该先contractcollapse 在几个方面更通用,但你的 "sum" 实际上是一个计数或频率,所以 contract 更直接。

contract country response, freq(sum_)

reshape wide sum_, i(country) j(response)

list 

     +-------------------------+
     | country   sum_1   sum_2 |
     |-------------------------|
  1. |       A       4       4 |
  2. |       B       3       2 |
     +-------------------------+

在 Stata 16 中,help frames 引入了框架作为在同一会话中处理多个数据集的一种方式。