,我有以下數據:創建一個循環來排序數據一起
id date day_1...day_6...day_20 port_ent port_day_1...port_day_6...port_day_20
1 1/1/00 2 4 6 1 2 4 6
2 1/6/00 1 2 5 6 . 2 5
3 1/16/00 3 2 1 16 . . 1
4 1/20/00 6 3 2 20 . . 2
我想創建變量port_day_i
。
day_i
:給定date
多少小部件是在第i 出售第天(當i
= 1,這是在同一天date
)
port_ent
:使用id = 1
作爲port_day_1
port_day_i
:在那個投資組合日,每個人的銷售額是多少
您入境的那一天呃組合從day_1
使用數據,然後第二天你day_2
等
我想這個循環會工作,但它並不:
forval j = 2/100 {
local i = `j' - port_ent + 1
gen port_day_`j' = .
replace port_day_`j' = day_`i' if `i' > 0
}
此代碼將讓我有一部分的方式但顯然,這將是非常麻煩的,我有超過1000天的數據
gen port_day_1 = .
replace port_day_1 = day_1 if port_ent == 1
gen port_day_2 = .
replace port_day_2 = day_2 if port_ent == 1
replace port_day_2 = day_1 if port_ent == 2
gen port_day_3 = .
replace port_day_3 = day_3 if port_ent == 1
replace port_day_3 = day_2 if port_ent == 2
replace port_day_3 = day_1 if port_ent == 3
gen port_day_4 = .
replace port_day_4 = day_4 if port_ent == 1
replace port_day_4 = day_3 if port_ent == 2
replace port_day_4 = day_2 if port_ent == 3
replace port_day_4 = day_1 if port_ent == 4
gen port_day_5 = .
replace port_day_5 = day_5 if port_ent == 1
replace port_day_5 = day_4 if port_ent == 2
replace port_day_5 = day_3 if port_ent == 3
replace port_day_5 = day_2 if port_ent == 4
replace port_day_5 = day_1 if port_ent == 5
gen port_day_6 = .
replace port_day_6 = day_6 if port_ent == 1
replace port_day_6 = day_5 if port_ent == 2
replace port_day_6 = day_4 if port_ent == 3
replace port_day_6 = day_3 if port_ent == 4
replace port_day_6 = day_2 if port_ent == 5
replace port_day_6 = day_1 if port_ent == 6
如果你把下方的'當地i'一個'display'一行(並註釋掉一切) ,你會在你的循環中看到'i = j'。試着用'display'i =「\'i'」,j =「\'j''並親眼看看。我想這是無意的。根據問題的措辭,我實際上無法理解你所尋求的。也許你甚至不需要循環。 –
@RobertoFerrer我正在嘗試創建'port_day_i'列。我假設我的'i'的錯誤指示是我的主要問題,但我不知道如何解決它。我打開一個非循環的答案,但我不確定這會起作用。 – CJ12
@RobertoFerrer如果這有幫助:初始'i'對於記錄應該是唯一的,並且應該在每個記錄的每次迭代中(從該初始'i')增加1。 – CJ12