2014-07-07 83 views
1

我想使用Stata的collapsesummarize。說我有數據(1的對應於同一個人,這樣做對2的和3的),當summarize d,看起來是這樣的:使用摺疊像總結

 Obs Mean Std. Dev. Min Max 
Score1 54  17   3  11 22 
Score2 32  13   2  5  28 
Score3 43  22   4  17 33 
Value1 54  9   3  2  12 
Value2 32  31   7  22 44 
Value3 43  38   4  31 45 
Speed1 54  3   1  1  11 
Speed2 32  6   3  2  12 
Speed3 43  8   2  2  15 

我將如何建立一個新的數據集(使用collapse什麼其他),看起來有點像summarize給出的,但看起來像以下?請注意,變量之後的數字對應於我的數據中的觀察值。所以Score1,Value1Speed1都對應於_n == 1。

_n ScoreMean ValueMean SpeedMean ScoreMax ValueMax SpeedMax 
1  17   9   3  22  12  11 
2  13   31   6  28  44  12 
3  22   38   8  33  45  15 

(我省略了標準偏差和最小值爲簡潔。)

當我運行collapse (mean) Score1 Score2 Score3 Value1 Value2 Value3 Speed1 Speed2 Speed3,我得到以下,這是不是非常有幫助:

 Score1 Score2 Score3 Value1 Value2 Value3 Speed1 Speed2 Speed3 
1 17  13  22  9  31  38  3  6  8 

這是在正確的軌道上。不過,它只給了我意思。我不知道如何讓它給我多個統計一次。我想我需要在某個時候以某種方式使用reshape

回答

2

這從Roberto的示例玩具數據集開始。我認爲它更容易推廣到800個物體。 (順便說一句,在Stata _n總是和只意味着當前的數據或by:定義的組觀察數量,因此您的使用是語法的輕微濫用)。

clear 
input score1 score2 value1 value2 speed1 speed2 
5 8 346 235 80 89 
2 10 642 973 65 78 
end 

gen j = _n 
reshape long score value speed, i(j) j(i) 
rename score yscore 
rename value yvalue 
rename speed yspeed 
reshape long y, i(i j) j(what) string 
collapse (mean) mean=y (min) min=y (max) max=y, by(what i) 
reshape wide mean min max, j(what) i(i) string 
+0

感謝您的答案和澄清'_n'。 – bill999

3

的一種方式,跟隨引導:

*clear all 
set more off 

input /// 
score1 score2 value1 value2 speed1 speed2 
5 8 346 235 80 89 
2 10 642 973 65 78 
end 

list 

summarize 

*----- 

collapse (mean) score1m=score1 score2m=score2 /// 
    value1m=value1 value2m=value2 /// 
    speed1m=speed1 speed2m=speed2 /// 
    (max) score1max=score1 score2max=score2 /// 
    value1max=value1 value2max=value2 /// 
    speed1max=speed1 speed2max=speed2 

gen obs = _n 

reshape long [email protected] [email protected] [email protected] [email protected] [email protected] [email protected], i(obs) j(n) 
drop obs 

list 

問了幾個統計數據是很容易。使用[(stat)] target_var=varname語法,以便在請求多個統計信息時不會出現衝突的名稱。然後,reshape

如果有很多變量/主題,它會變得非常單調乏味。還有其他方法。如果以後沒有人提供替代方案,我會稍後修改答案。

+0

哇 - 太感謝你了。這完美的作品! 只要有很多變量 - 有800個,所以我會有從1到800的_n。 – bill999