我正在尝试编写一个Stata程序,该程序通过标识符进行一些计算,并且希望这样做,以便标识符可以是字符串或整数。
我正在尝试做的一个非常简化的版本是这样的:
clear all
***** test data
input str10 id1 id2 x y
a 1 20 40
a 1 140 20
a 1 0 70
b 2 50 25
b 2 25 50
b 2 40 42
end
*****
capture program drop myprog
program define myprog
version 14.2
syntax using, ID(varname) Mean(varname)
tempname postname
quietly levelsof `id', local(ids)
local idtype: type `id'
postfile `postname' `idtype' `id' `mean' `using', replace
foreach i of local ids {
quietly summarize `mean' if `id'==`i'
post `postname' (`i') (`r(mean)')
}
postclose `postname'
end
我希望以下两项都能起作用:
myprog using "test1.dta", id(id1) mean(x)
myprog using "test2.dta", id(id2) mean(x)
有什么建议吗?
答案 0 :(得分:2)
只需使用if
/ else
语句来区分这两种情况:
capture program drop myprog
program define myprog
version 14.2
syntax using, ID(varname) Mean(varname)
tempname postname
quietly levelsof `id', local(ids)
local idtype: type `id'
postfile `postname' `idtype' `id' `mean' `using', replace
if substr("`idtype'" , 1, 3) == "str" {
foreach i of local ids {
summarize `mean' if `id'=="`i'", meanonly
post `postname' ("`i'") (`r(mean)')
}
}
else {
foreach i of local ids {
summarize `mean' if `id'==`i', meanonly
post `postname' (`i') (`r(mean)')
}
}
postclose `postname'
end
顺便提一下,请注意meanonly
的{{1}}选项的使用。
答案 1 :(得分:0)
这就是我最终要做的:
capture program drop myprog
program define myprog
version 14.2
syntax using, ID(varname) Mean(varname)
tempname postname
quietly levelsof `id', local(ids)
local idtype: type `id'
postfile `postname' `idtype' `id' `mean' `using', replace
capture confirm string variable `id'
if !_rc {
foreach i of local ids {
quietly summarize `mean' if `id'=="`i'"
post `postname' ("`i'") (`r(mean)')
}
}
else {
foreach i of local ids {
quietly summarize `mean' if `id'==`i'
post `postname' (`i') (`r(mean)')
}
}
postclose `postname'
end
两个几乎相同的循环看起来很难看,但是我想那很好。