




免费预览已结束,剩余166页可下载查看
下载本文档
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Lecture 1 - Table of ContentsWelcomeEntering and executing a programMechanical method 1: The do-fileAside: Built in do-file editorMechanical method 2: the interactive program commandMechanical method 3: program in a do-fileMechanical method 4: combination do-filesMechanical method 5: ado filesAside: Using Stata and an editor or word processorOrganizing do-filesAn individual do-fileA do-file to perform verificationInfiling dataAside: Working with datasets that are too largeReproducibilityIndexingassert as an alternative to branchingConsuming calculated resultsExercisesConclusionAppendix A: Sample data for hierarchical dataset exampleAppendix B: Sample data for relation example WelcomeWelcome to NetCourse 151 - An Introduction to Stata Programming. Before we get started there are a few things we need to get out of the way. In the NetCourse Basics message we showed those with a web-aware Stata how to use Stata to automatically download the important cutouts for each lecture. You will want to do that now for lecture 1. For instance, within Stata you would move to your course directory (using the cd command), create a directory for this lecture, and download the files. Here is what I did: . cd C:nc151 . mkdir lecture1 . cd lecture1 . run /courses/nc151-8/lec1.doReread the NetCourse Basics message for more details on this command. In this lecture we discuss How to enter a program and execute it Programming as automating data management and analysis The importance of organization, especially as it pertains to reproducibility The importance of data verification Simple data checks and debugging (assert and trace) Working with datasets that are too large to fit in memory Reading a hierarchical datasetBack to Table of ContentsEntering and executing a programThis is a course about programming Stata, but before we can get into the details of programming, you need to master the mechanics of programming. You need to learn how to enter a program into Stata and how to get Stata to execute it. A famous book on programming began with a program to do nothing more than display the text Hello, world. This was clever because it eliminated all programming complexity; However, that still left the considerable complexity of dealing with the compiler. We will do the same thing by writing a program with a body of . display Hello, worldHello, worldWe will deal more with the display command later, but right now, when you see display Hello, world, you are supposed to imagine that it stands for something longer and more elegant. Then you should ignore that fact and look at all the Stata junk around it - the stuff that turned the body display Hello, world into a program that can be executed over and over again. Typographical note: From now on, commands issued to Stata will be in bold black text. Back to Table of ContentsMechanical method 1: The do-fileA do-file is just an ASCII file (plain text file with no special characters) containing Stata commands that you create with an editor or word processor. When you interactively type do filename at the keyboard, the contents of file are executed just as if you typed each line at the keyboard. BEGIN hello.dodisplay Hello, worldEND hello.doYou run this program by interactively typing . do hello-you type this. display Hello, world-Stata types thiswhich displays the following in the Stata Results window Hello, world.end of do-file . Save As. Name the new file hello.do, and make sure that you save it in your current (working) directory. Now, either close the do-file editor (click on the X), or push it aside. In the Stata command window, type do hello and press Enter.Although this seems simple enough, it may not work when you try it. There is a lot, mechanically, that can go wrong (which is why you should try it - it will be easier to master these problems now, with this one-line do-file, than to wait and face the problems in a complicated case). What might go wrong: You enter your word processor or editor, enter hello.do, and save it. You try to do it from Stata and are told file hello.do not found. o Solution: hello.do is not in the current directory. Either copy the file to the current directory using your operating system, or use cd to change to the directory containing the do-file. Another possibility: it is in the current directory, but you did not name it hello.do. Say you named it hello.pgm. Then you would execute it by typing do hello.pgm. Say you named it simply hello. Then you would execute it by typing do hello. (note: the period is part of the command). Stata do-files have a default suffix: .do When you type do X, Stata assumes you mean do X.do. If the suffix is other than the default, you must specify it. If there is no suffix, you put a period at the end. File hello.do is found, but what is displayed is nothing like what you entered when you do it. o Solution: You did not save hello.do as an ASCII file, but saved it as some sort of document. If you use a word processor to enter do-files, you must save them as ASCII files. File hello.do is found, it appears okay, but it does not do anything. That is, when you run it you see . do hello . display Hello, world Note that Stata executed the display command but never displayed Hello, world. o Solution: You forgot to end the single line in the do-file with a hard return. The line is not terminated, so Stata ignored it. Go back and add the return. Make sure to save your file. Perhaps something else could happen; if so, email us at . In the meantime, if you ran into this last problem, we have a suggestion: end all of your do-files with the word exit. exit, in a do-file, does not exit Stata but exits the do-file. Thus, we recommend that you enter your do-file as BEGIN hello.dodisplay Hello, worldexitEND hello.doThere are now two possibilities: either you remembered to put the hard return after the exit, or you did not. Either way, it will not matter. If you remembered, Stata will see the command exit and exit the do-file. If you did not, Stata will not see exit, the do-file will end, and Stata will still exit the do-file. With the exit command in place, you could not have forgotten the hard return at the end of display Hello, worldbecause, if you had, that command would display in your word processor as being run together with the exit command: display Hello, worldexitBack to Table of ContentsMechanical method 2: the interactive -program- commandAnother way to enter our program would be to interactively type . program hello 1. display Hello, world 2. endand when we want to execute it, type . helloHello, worldDo this. You have just created your first Stata command. You will seldom want to define your programs interactively, but it is easier to learn what a command can and cannot do for us by trying it interactively. As with do-files, things can go wrong: Problem 1: program redefinition. You want to change the program hello to display Hi back rather than Hello, world. You type: . program hello hello already defined r(110); Stata remembers definitions throughout the session, so you cannot redefine a program until you drop the old version: . program drop hello. program hello 1. display Hi back 2. end. helloHi back. Problem 2: program does not know about built-in command names. Lets enter our Hello, world program and call it b: . program b 1. display Hello, world 2. end. bHello, world Fine, that works. Now lets call it d: . program d 1. display Hello, world 2. end. dContains data obs: 0 vars: 0 size: 0 (99.9% of memory free) Sorted by: What happened? d is the Stata abbreviation for the built-in Stata command describe. program let us define a program called d, but there is no way we can execute it because Statas built-in commands take precedence. How can you find out if a name is already taken? Use Statas which command: . which d built-in command: describe . which b command b not found as either built-in or ado-file r(111); Problem 3: program does not check syntax. The syntax of program is program program-name 1. content of program more program etc. 2. end Between the program and the end, Stata merely stores whatever you type. Stata does not determine whether what you type makes sense until you try to execute it. . program hello 1. display Hello, world 2. end. helloHello not foundr(111); In this case, we omitted the double quotes around Hello, world. In our one-line program, finding the error is easy. Where else could it be than on line 1? If our program were 50 lines long, finding it would be more difficult. Stata can trace the execution of a program: . set trace on. hello- display Hello, worldHello not foundr(111);. set trace off One thing to remember: if you set trace on, do not forget to turn it back off afterwards. Otherwise, youll run some other Stata command and be surprised by the amount of output produced. Hints for debugging large, complicated programs: . set trace on /* turn on tracing */. set more off /* turn off -more- */. log using junk, replace /* start a log */. invoke program Output will scroll by without -more- ever appearing. Eventually, the error will occur. Then, . log close. set more on /* turn back on -more- */. set trace off /* turn off trace */ Now you can look at junk.log using the Viewer. Problem 4: theres a limit to how big a program can be. A single program program must contain fewer than 3,500 lines and less than 135,600 characters in Intercooled Stata and Stata/SE. In Small Stata the limit is 1,000 lines. Actually, the Intercooled Stata and Stata/SE limit is 135,600 characters, and the Small Stata limit is 37,296 characters after a little compression Stata performs. This, in practice, is not a problem because a) 3,500 lines are a lot, andb) programs can call other programs. Nevertheless, we sometimes write programs that are too big and then have to go back and split them into pieces. Problem 5: there is no way to edit a program after you haver entered it. You can define programs interactively, you can execute programs interactively, and you can drop programs interactively, and that is it. Not only can you not edit the program, but there is no way to store it. This makes the interactive definition of a program not useful. Note that by interactively, we mean at the command line prompt. Think of the Stata do-file editor as a separate thing. Back to Table of ContentsMechanical method 3: -program- in a do-fileIf program can be used interactively, and if do-files execute lines as if they were entered interactively, then do-files can contain programs. The advantage, of course, is that because you enter do-files using your editor or word processor, you can edit programs and store them. BEGIN hello.doprogram hellodisplay Hello, worldend exitEND hello.doSo, lets try it: . do hello- we type interactively . program hello- Stata responds hello already defined r(110); end of do-file r(110);Why didnt that work? Because we have already defined a program called hello (in preparing this lecture, we have been working in Stata interactively, and hello is left over from a previous example). So, lets drop the hello program and try again: . program drop hello- we type interactively . do hello- we type . program hello- Stata types 1. display Hello, world 2. end . exit end of do-fileLook carefully at what just happened: the program hello was not executed. Do-files contain lines that Stata executes as if you typed them in from the keyboard, and our do-file contains BEGIN hello.doprogram hellodisplay Hello, worldend exitEND hello.doNowhere in the do-file do we call on hello to be executed, so Stata does not execute it. In this case, because our program is now loaded, we can execute it interactively: . hello Hello, worldIn do-files that merely define programs, we typically do not want to see the program lines scroll by when we load them. It is more convenient to load such programs using run, which is the same as do but suppresses the output: . program drop hello - we type, so we can reload. run hello - we type, hello.do runs silently . hello Hello, worldBack to Table of ContentsMechanical Method 4: combination do-filesDo-files execute whatever commands we include in them. We do not have to merely define our program in the do-file - we could define our program and run it, or define numerous programs, or define numerous programs and run them. Anything we can do interactively - thats almost everything Stata can do - we can do in a do-file. So, here is our do-file modified to load and execute our program: BEGIN hello.doprogram hellodisplay Hello, worldend helloexitEND hello.doNow we can interactively type . do hello- we type . program hello- Stata responds hello already defined r(110); end of do-file r(110);Oops! . program drop hello- we type . do hello- we type . program hello- Stata responds 1. display Hello, world 2. end . hello Hello, world. exit end of do-file .- our turn to type againHaving to remember to type program drop hello is tedious. Since do-files execute whatever we put in them just as if we were typing from the keyboard, we can put the program drop into our do-file: BEGIN hello.doprogram drop helloprogram hellodisplay Hello, worldend helloexitEND hello.doNow we can type do hello when hello is already defined, and it will redefine hello and run the redefined program. There is, however, a problem. What if hello is not already defined? . program drop hello - we type . do hello - we type . program drop hello - Stata types hello not found r(111); end of do-file r(111);We fixed our do-file to redefine hello when it was already defined but broke it in cases when hello was undefined anyway. Ultimately, you will come to appreciate that this stop-on-error behavior of do-files is a useful feature, but right now, it is merely an irritation. Right now, we do not care whether program drop hello works or not. If it works, then it needed to be done. If it does not work, it wasnt needed anyway. If you put the word capture in front of a Stata command, its error status is ignored. Typing capture X does the same thing as X, but after X completes, any errors are reset, so it is as if the error did not happen. (capture X does more than that - it stores the error, if any, so that subsequent commands can find out about it - well use that feature in a later lecture - and it catches all the output generated by X - including error messages - and discards it; see Exercise 3.) So, here is a version of our program that will run whether or not hello is already defined: BEGIN hello.docapture program drop helloprogram hellodisplay Hello, worldend helloexitEND hello.doBack to Table of ContentsMechanical method 5: ado filesThis is an extension of Mechanical Method 3: a program in a do-file. If such a files name is simply changed from X.do to X.ado, you do not have to load the program before executing it. Thus, we can add the command hello to Stata by taking BEGIN hello.doprogram hellodisplay Hello, worldend exitEND hello.doand simply renaming it hello.ado BEGIN hello.adoprogram hellodisplay Hello, worldend exitEND hello.adoYou should try this and test it: . program drop hello - just to prove hello not loaded. hello Hello, worldado stands for automatically loaded do-file. When you type X, If X is a built-in command of Stata, Stata executes it. Failing that, if X is a defined program, Stata executes it. Failing that, Stata looks for X.ado. If X.ado exists, o Stata issues to run X.ado to itself o If that works, Stata verifies that X is now a defined program. o If it is, Stata reissues X to itself. Failing that, Stata returns unrecognized command. Aside: Using Stata and an editor or word processorIf you are going to program in Stata, you will want to jump between Stata and your editor or word processor (Ill use the word editor from now on). One solution is to learn how to use Statas built-in do-file editor. Try it - the command is doedit (or you can press the do-file editor icon) for Windows, Macintosh, and Unix(GUI) users. The other version of Stata, the Unix(console
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年农村食品安全管理模拟题及参考答案详解
- 2025年AI运维工程师容器编排面试题(含答案与解析)
- 2025年产品设计经理初级面试要点及预测题
- 2025年传统民族音乐演奏技巧认证题库
- 货运汽车队管理办法
- 规范软件使用管理办法
- 15.2.2 分式的加减(第1课时)说课稿 2025-2026学年人教版数学八年级上册
- 网上营业厅管理办法
- 中外旅行社组团合同书3篇
- 2025年医药销售代表招聘面试指南及行业知识分析预测题
- 土地合作协议书合同模板
- 2025水利安全员C证考试题库(含答案)
- 合同保证金转让三方协议
- 一级建造师-机电工程管理与实务-案例专题突破教学课件
- 新沪教牛津版九年级上册英语全册教案
- 2025人教版(2024)一年级上册数学教学计划 (三篇)
- 无人机原理课件
- 1.1 精微广大-绘画的功能和种类 教学设计-2023-2024学年高中美术人美版(2019)选择性必修1 绘画
- 全校教学质量提升会上校长讲话:把每一节课教好是我们最实在的荣耀
- 体适能教学课件培训
- 市场监督局知识培训课件
评论
0/150
提交评论