Stata编程|基础命令

0.常用便捷命令

0.1 levelof

levelsof displays a sorted list of the distinct values of varname

levelsof 可以帮助我们了解指定变量的取值情况

*Synax
levelsof varname [if] [in] [, options]

假设我们想知道auto.dta中变量rep78都有哪些取值

cls
sysuse auto, clear
levelsof rep78

1 2 3 4 5

0.2 fs

fs lists the names of files in compact form.

fs 可以列示指定路径下的指定类型的文件,结果存储在返回值r(files)中。需要注意的是fs是外部命令,首次使用时需要安装。

*Synax
fs [filespec [filespec [ ... ]]]

假设我们想知道某一文件夹内有哪些dta文件

cls
ssc install fs
cd D:\software\stata16\Stata16MP\ado\base\a
fs *.dta

auto.dta     auto2.dta    autornd.dta

return list

macros:
              r(files) : ""auto.dta" "auto2.dta" "autornd.dta" "

0.3 rmsg

set rmsg determines whether the return message is to be displayed at the completion of each command. The initial setting is off. The return message shows how long the command took to execute and what time it completed execution.

rmsg可以帮助我们了解代码运行的时间,以便优化代码。

# Synax
set rmsg [on | off]  [, permanently]

假设我们我们想知道从1循环到100000需要多久

cls
set rmsg on 
forvalues k = 1(1)100000{
    display `k'
}

...
99997
99998
99999
100000
r; t=0.87 0:39:24

0.4 log

log可以将输入及输出等过程内容保存到文件中

*报告日志文件状态
log
log query [logname | _all]

*生成并打开日志文件
log using filename [, append replace [text|smcl] name(logname) nomsg]

*关闭日志
log close [logname | _all]

*暂停或继续日志记录
log off [logname]
log on [logname]

使用auto数据集给出一个简单的例子

log using log_auto, name(log1)
sysuse auto, clear
drop if rep78 ==.
save test3, replace
log close log1

宏的知识较多,以后再另写推文

1.循环

1.1 while

while evaluates exp and, if it is true (nonzero), executes the stata commands enclosed in the braces. It then repeats the process until exp evaluates to false (zero).

while 是依据表达式的真假进行循环,后面的forvalues和foreach可以理解为是while的
变种。

*Synax
while exp { 
     stata_commands 
}

下面给出单循环和嵌套循环的简单例子

*单循环
local j = 1
while `j' < 10{
    display `j'
    local j = `j' + 1
}

*嵌套循环
local i = 1
while `i' <= 5{
    local j = 1
    while `j' < `i'{
        display "`j' 小于 `i'"
        local j = `j' + 1
    }
    local i = `i' + 1
}

再补充个用while求解方程的例子

local x_est = 0
while abs(`x_est' ^ 2 - 4 * `x_est' + 4 - 0) > 0.0000001{
    local x_est = `x_est' + 0.001
}
display in red `x_est'

2

1.2 forvalues

Loop over consecutive values

forvalues 只能用于数值的循环

*Synax
forvalues lname = range {
  Stata commands referring to `lname'
 }

对于while中方程求解例子,我们也可以用forvalues来做,假如我们猜到解在1-3范围内

forvalues x_est = 1(0.0001)3{
    if abs(`x_est' ^ 2 - 4 * `x_est' + 4 - 0) < 0.000000001{
        display in red `x_est'
        continue, break
    }
}

2

1.3 foreach

foreach repeatedly sets local macro lname to each element of the list and executes the commands enclosed in braces. The loop is executed zero or more times; it is executed zero times if the list is null or empty.

foreach后面跟的对象可以是宏、变量名和文件名等,比forvalues的适用性更强。

foreach lname 
in | of listtype    
list {
commands referring to ‘lname’ }

Allowed are
  foreach lname in any list {
  foreach lname of local lmacname {
  foreach lname of global gmacname {
  foreach lname of varlist varlist {
  foreach lname of newlist newvarlist {
  foreach lname of numlist numlist {

假设我们想逐个显示auto.dta中变量make的值,以下两种方式是等价的,但更推荐使用of方式。

cls 
sysuse auto, clear
levelsof make, local(make_info)
set rmsg on 
foreach x of local make_info{
    display "`x'"
}

cls 
sysuse auto, clear
levelsof make, local(make_info)
set rmsg on 
foreach x in `make_info'{
    display "`x'"
}

set rmsg off

通过foreach和其他命令的搭配,我们可以让电脑帮忙做些重复性工作。

*在指定文件夹依次生产名称为2010-2018的excel表格
cd C:\Users\Van\Desktop\test1
foreach file_name of numlist 2010/2018{
    putexcel set `file_name'.xlsx, replace
    putexcel A1 = "Year"
    putexcel B1 = "Variable"
    putexcel C1 = "Varlue"
}

*以上用forvalues实现更简单、速度更快

*将上面生产的excel文件转换成dta格式
local xlsx_list: dir . files "*.xlsx"
foreach excel_file of local xlsx_list{
    display "`excel_file'"
    import excel using `excel_file', firstrow clear
    save `excel_file'.dta, replace  
}

#批量计算并查看变量的均值
cls
sysuse auto, clear
foreach v of varlist price mpg weight length{
    quietly summarize `v'
    display "mean of variable `v' is:"  `r(mean)'
}

1.4 continue

The continue command within a foreach, forvalues, or while loop breaks execution of the current loop iteration and skips the remaining commands within the loop. Execution resumes at the top of the loop unless the break option is specified, in which case execution resumes with the command following the looping command.

有时在做循环运算时,需要根据某种情况终止循环,此时可以使用continue

*synax
continue [, break]
  • continue:中止当前循环余下所用命令,返回上一级循环
  • continue, break:中止全部循环余下所用命令,返回上一级循环
*continue
forvalues i = 1(1)5 {
    disp `i'
    if `i' >2{
        continue
    }
    disp "`i':Hello World"
}


1
1:Hello World
2
2:Hello World
3
4
5

*continue, break
forvalues i = 1(1)5 {
    disp `i'
    if `i' >2{
        continue, break
    }
    disp "`i':Hello World"
}

1
1:Hello World
2
2:Hello World
3

2.条件判断

The if command evaluates exp. If the result is true (nonzero), the commands inside the braces are executed. If the result is false (zero), those statements are ignored, and the statement (or statements if enclosed in braces) following the else is executed.

*synax
if exp {     or     if exp single_command
       multiple_commands
}

else {        or    else single_command
     multiple_commands
}

假设我们想写个计算小程序,当n>0时,表达式为x^n; 当n=0时,表达式是log(n);当n<0时,表达式是-x^n

program power
    if `2' > 0 {
        display in red `1'^`2'
    }
    else if `2' == 0 {
        display in red log(`1')
    }
    else {
        display in red -(`1'^(`2'))
    }
    end

power 16 2

256

3.数据恢复

Preserve and restore data

在数据处理的过程中失误不可避免,这会导致数据被覆,于是我们只能从头处理。面对这种情况,在处理时添加preserve会很有帮助。

*synax
preserve [, changed]
restore [, not preserve]

我们随机生产一组数据,它是由year和value组成,现在想把同一年的数据单独提取出来分别保存。我们很容易能想到使用如下命令

keep if year == 2015
save 2015.dta, replace

但是执行了上述命令后,原始数据就会被更改,除了2015年外其他年份的样本均会被删除,这使得我们只能写多次keep if 命令。此时,可以使用preserve和restore解决问题。

clear
set seed 12345
set obs 10
gen year = _n + 2009
expand 3
gen value = uniform()
save test2, replace

use test2, clear
forvalues i = 2009/2019{
    preserve
    keep if year == `i'
    save `i', replace
    restore
}

4.异常处理

capture executes command, suppressing all its output (including error messages, if any) and issues a return code of zero. The actual return code generated by command is stored in the built-in scalar _rc.

在日常数据处理,我们需要程序在遇到错误时自动跳过,此时添加capture即可。

*synax
capture [:] command

capture {
    stata_commands 
}

我们可以通过对比以下两段代码返回值差异来认识capture的作用。

hist 杭州
dis "杭州"

no variables defined
capture hist 杭州
dis "杭州"

杭州

进一步地,我们可以再添加noisily以显示错误情况

capture noisily hist 杭州
dis "杭州"

no variables defined
杭州

使用display _rc可以查看错误返回值

capture noisily hist 杭州
dis "杭州"
display _rc

111

如果代码正常运行有_rc=0

capture noisily display "杭州"
display _rc

0

capture也可以包括一批命令

capture noisily {
    di "杭州"
    error
    di "上海"
}

杭州
invalid syntax
r(197);

需要注意“上海”没有显示,这是因为一旦报错,capture命令直接跳到了括号外边,结束运行。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容

  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 4,352评论 0 5
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,267评论 0 10
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,703评论 0 38
  • 黑色的海岛上悬着一轮又大又圆的明月,毫不嫌弃地把温柔的月色照在这寸草不生的小岛上。一个少年白衣白发,悠闲自如地倚坐...
    小水Vivian阅读 3,090评论 1 5
  • 渐变的面目拼图要我怎么拼? 我是疲乏了还是投降了? 不是不允许自己坠落, 我没有滴水不进的保护膜。 就是害怕变得面...
    闷热当乘凉阅读 4,231评论 0 13