2017-08-28 66 views
0

我有數據集顯示人們在10分鐘的時間間隔內花了30分鐘的時間。將每人累計變量擴展到時間間隔變量

Person  cumulative_time Activity 
A    10    Game 
A    30    Eat 
B    10    Sleep 
B    20    Game 
B    30    Sleep 

which means person A did gaming during the first 10 minutes, 
and eating during the next 20 minutes, 
and person B was sleeping for the first 10 min, 
gaming for the next 10 min, and sleeping for the last 10 mins. 

我想重構數據集。每一行將是每個獨特的人。

然後,每列將會是這樣的每個時間間隔。

Person   time10 time20   time30 
A    Game   Eat   Eat 
B    Sleep  Game   Sleep 

我知道我可以使用「崩潰」使人獨特,但我不知道這可以如何用於我的目的。 「重塑」命令做了類似的事情,但我再也找不出如何使用它來做我想做的事情。

回答

1

重塑是解決這個問題的方法。像這樣的東西可能會完成你所需要的。

clear 
input str1 Person int cumulative_time str8 Activity 
A    10    Game 
A    30    Eat 
B    10    Sleep 
B    20    Game 
B    30    Sleep 
end 
rename Activity time 
reshape wide time, i(Person) j(cumulative_time) 
replace time20 = time10 if missing(time20) 
replace time30 = time20 if missing(time30) 
list, clean 

如果您的問題有許多cumulative_time值,而不僅僅是三個,我會以不同的方式解決缺失值的問題。

+0

謝謝您的回答!但是你的代碼的結果與我想要的結果有所不同。它應該是遊戲,吃,吃。不是遊戲遊戲吃 – user42459

+0

您可以自由地對我的代碼進行必要的微小更改以使其滿足您的需求 - 讀取代碼並找出命令執行的操作,然後修復它們。 – 2017-08-28 21:50:49

1

除了威廉Lisowski答案,這裏是用tssettsfill命令的方法:

clear 
input str1 Person int cumulative_time str8 Activity 
A    10    Game 
A    30    Eat 
B    10    Sleep 
B    20    Game 
B    30    Sleep 
end 
rename Activity time 

egen id = group(Person) 
tsset id cumulative_time, delta(10) 
tsfill, full 

bysort id : replace Person = Person[_n-1] if Person=="" 
bysort id : replace time= time[_n+1] if time=="" 
drop id 

reshape wide time, i(Person) j(cumulative_time) 
list, clean 

,輸出:

 Person time10 time20 time30 
    1.  A  Game  Eat  Eat 
    2.  B Sleep  Game Sleep