Stata编程和putexcel循环
问题描述:
我正在尝试使用putexcel和一个简单的程序来创建一个自动化的Excel文件,该文件记录了在构建示例期间掉落的观察次数。Stata编程和putexcel循环
我很新的编程,但下面的程序完成这项工作。它存储4个全局宏,每次我放弃一些观察结果:1)丢弃的观察数量,2)观察到的分享数量下降,3)留在数据集中的观察数量,以及4)描述为什么我放弃观察结果的字符串。
要将结果导出为excel我使用putexcel命令 - 它工作正常。问题是我需要在dofile中多次删除观察结果,我想知道是否可以将putexcel部分合并到程序中以使其在单元中循环。
换句话说,我想要的是第一次在A1中第二次自动保存描述($ why)的程序,依此类推。
我已经提供了我下面的代码示例:
** Generate some data:
clear
input id year wage
1 1 200
1 2 250
1 3 300
2 1 152
2 2 150
2 3 140
3 1 300
3 2 320
3 3 360
end
** Define program
cap program drop dropdata
program define dropdata
count
global N = r(N)
count if `1'
global drop = r(N)
global share = ($drop/$N)
drop if `1'
count
global left = r(N)
global why = "`2'"
end
** Drop if first year
dropdata year==1 "Drop if first year"
** Export to excel
putexcel set "documentation.xlsx", modify
putexcel A1 = ("$why")
putexcel A3 = ("Obs. dropped") A4 = ("Share dropped") A5 = ("Observations left")
putexcel B3 = ($drop) B4 = ($share) B5=($left)
** Now drop if wage is < 300
dropdata wage<300 "Drop if wage<300"
putexcel A8 = ("$why")
putexcel A10 = ("Obs. dropped") A11 = ("Share dropped") A12 = ("Observations left")
putexcel B10 = ($drop) B11 = ($share) B12 = ($left)
答
这样做的问题是,塔塔不知道被填补,这是什么细胞都没有,所以我认为这很可能是最简单的,包括您的program define
中的另一个参数说明您运行程序的次数。
下面是一个例子:
** Generate some data:
clear
input id year wage
1 1 200
1 2 250
1 3 300
2 1 152
2 2 150
2 3 140
3 1 300
3 2 320
3 3 360
end
** Define program
cap program drop dropdata
program define dropdata
count
local N = r(N)
count if `1'
local drop = r(N)
local share = ($drop/$N)
drop if `1'
count
local left = r(N)
local why = "`2'"
local row1 = `3'*7 + 1
local row3 = `row1' + 2
local row4 = `row1' + 3
local row5 = `row1' + 4
putexcel set "documentation.xlsx", modify
putexcel A`row1' = ("`why'")
putexcel A`row3' = ("Obs. dropped") A`row4' = ("Share dropped") A`row5' = ("Observations left")
putexcel B`row3' = (`drop') B`row4' = (`share') B`row5' = (`left')
end
** Drop if first year
dropdata year==1 "Drop if first year" 0
** Now drop if wage is < 300
dropdata wage<300 "Drop if wage<300" 1
注意的变化是包括已经完成在dropdata第三个参数调用的次数,那么我们添加putexcel命令,基于该行数。
顺便说一句:
我改变了所有的全局的当地人,因为他们是更安全的。此外,在一般情况下,如果你想从你写一个程序返回宏,你告诉Stata的程序是,例如rclass
,然后使用如下语句:
program define return_2, rclass
return local asdf 2
end
,然后你可以访问本地asdf(等于2)作为本地r(asdf)
,您可以使用以下命令检查程序返回的所有当地人的值:return list