创建循环以将数据排序在一起

时间:2013-11-22 22:00:15

标签: loops stata

我有以下数据:

 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 th 天销售了多少小部件(当i = 1时,这与{{{ 1}})

date:使用port_ent作为id = 1的标准化日期系统

port_day_1:在该投资组合日,每个人的销售额是什么

您输入投资组合的那天,您使用port_day_i的数据,然后第二天使用day_1等。

我认为这个循环可行,但它没有:

day_2

这段代码会让我分道扬but,但显然这会非常麻烦,我有超过1000天的数据

forval j = 2/100 { 
local i = `j' - port_ent + 1
    gen port_day_`j' = .
    replace port_day_`j' = day_`i' if `i' > 0
}

3 个答案:

答案 0 :(得分:1)

也许这会奏效。我无法理解你问题背后的逻辑。我怀疑它有一个bug,但尝试一下。我不得不更改一些变量名称并发明一些数据以便更好地理解。最后,我的变量sales_i是您的day_i而我的port_sales_j是您的port_day_j

clear all
set more off

input id  str15 date day_1 day_2 day_3 day_4 day_5 day_6 port_ent
  1  "1/1/00"     2      4       6    9    3   21   1 
  2  "1/3/00"     1      1       5    2    4   6   3   
  3  "1/6/00"     1      2       5    1    8   76   6
end

list

reshape long day_, i(id) j(day)
rename day_ sales
list, sepby(id)

sort id day
gen port_sales = .
by id: replace port_sales = sales[_n -(port_ent - 1)] if port_ent <= day
list, sepby(id)

reshape wide port_sales sales, i(id) j(day)
list id port_ent sales* 
list id port_ent port_sales*

答案 1 :(得分:0)

一个问题是你的local不是也不能被矢量化,这是你似乎希望或假设的。因此你的本地宏

local i = `j' - port_ent + 1

将被解释为评估

产生的常数
local i = `j' - port_ent[1] + 1

在每次观察中。

更大的问题是您的数据结构不适合用途。您有跨行的面板数据,因此您的变量是转置的。

我认为,这给出了你所要求的本质,但你应该考虑最终的reshape wide是否必要。这部分取决于你想做什么,但对于最有可能的面板操作,这个数据结构最好留下很长时间。

clear 
input id    day_1   day_6 day_20   port_ent  
1      2      4       6           1   
2      1      2       5           6   
3      3      2       1          16   
4      6      3       2          20   
end 
reshape long day_ , i(id) 
gen day2 = day_ + port_ent - 1
rename day_ port_day
reshape wide port_day , i(id _j) j(day2)

答案 2 :(得分:0)

此解决方案涉及一个循环,并且在形式上与您原来的尝试更接近:

clear all
set more off

input id day_1 day_2 day_3 day_4 day_5 day_6 port_ent
  1   2      4       6    9    3   21   1 
  2   1      1       5    2    4   6   3   
  3   1      2       5    1    8   76   6
end

forval i = 1/6 { 
    generate port_day_`i' = .

    local j = 1
    while `j' <= `i' {
        replace port_day_`i' = day_`j' if port_ent == `i' - `j' + 1
        local j = `j' + 1
    }
}

list id port_ent day* 
list id port_ent port_day*