



















































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!




















































UCD Geary Institute Discussion Papers often represent preliminary work and are circulated to encourage discussion. Citation of such a paper should account for its provisional character. A revised version may be available directly from the author.
Any opinions expressed here are those of the author(s) and not those of UCD Geary Institute. Research published in this series may include views on policy, but the institute itself takes no institutional policy positions.
A Practical Introduction to Stata
Abstract This document provides an introduction to the use of Stata. It is designed to be an overview rather than a comprehensive guide, aimed at covering the basic tools necessary for econometric analysis. Topics cov- ered include data management, graphing, regression analysis, binary outcomes, ordered and multinomial regression, time series and panel data. Stata commands are shown in the context of practical examples.
Contents
1 Introduction 4 1.1 Opening Stata............................................ 4 1.2 Preliminaries............................................. 4 1.3 Audit Trails.............................................. 6 1.4 Getting Help............................................. 6 1.5 Importing Data............................................ 6 1.6 User Written Commands....................................... 6 1.7 Menus and Command Window................................... 7 1.8 Data browser and editor....................................... 7 1.9 Syntax................................................. 7 1.10 Types of Variables.......................................... 8
2 Data Manipulation 9 2.1 Describing Data........................................... 9 2.2 Generating Variables......................................... 9 2.3 if Commands............................................. 9 2.4 Summarising with tab and tabstat................................. 10 2.5 Introduction to Labels........................................ 10 2.6 Joining Datasets........................................... 11 2.7 Tabout................................................. 12 2.7.1 Tabout with Stata 9/10/11................................. 12 2.7.2 Tabout with Stata 8..................................... 12 2.8 Recoding and Strings......................................... 13 2.9 Missing Values............................................ 14 2.10 Macros, Looping and Programming................................. 14 2.11 Counting, sorting and ordering................................... 16 2.12 Reshaping Datasets.......................................... 17 2.13 Graphs................................................. 17 ∗Geary Institute & School of Economics, University College Dublin. PGDA Fellow, Harvard Center for Population and Development Studies. I gratefully acknowledge funding from the Health Research Board. This document is based on notes for the UCD MA econometrics module and a two day course in the UCD School of Politics. Preliminary, comments welcome. Email: [email protected]
15 Multinomial Logit Output...................................... 42 16 MFX for Multinomial Logit..................................... 43 17 xtdescribe Output.......................................... 46 18 xtsum Output............................................. 46 19 xttrans Output............................................ 47 20 Test For A Common Intercept.................................... 49 21 Random Effects Output....................................... 49 22 Fixed Effects Output......................................... 50 23 Comparison of Panel Data Estimators............................... 52 24 Correlation Between Income, Openness and Area......................... 55 25 OLS and IV Comparison....................................... 55 26 Testing for Weak Instruments.................................... 56
List of Figures
1 An example of a graph matrix chart................................ 18 2 Graph Example 1: Map....................................... 20 3 Graph Example 2: Labelled Scatterplot.............................. 20 4 A Problem With OLS........................................ 27 5 Problem Solved With Probit and Logit............................... 29 6 Autocorrelation Functions For Infant Mortality and GDP.................... 32 7 Partial Autocorrelation Functions For Infant Mortality and GDP................ 33 8 Using OLS To Detrend Variables.................................. 34 9 Health Distribution.......................................... 36 10 Height Distribution.......................................... 37 11 Ordered Logit Predicted Probabilities............................... 39 12 Multinomial Logit Predicted Probabilities............................. 41 13 BHPS Income............................................. 45 14 BHPS Income by Job Satisfaction................................. 46 15 Graph Matrix for Openess, Area and Income Per Capita..................... 53 16 Openness and Area.......................................... 54
Objective
The aim of this document is to provide an introduction to Stata, and to describe the requirements necessary to undertake the basics of data management and analysis. This document is designed to complement rather than substitute for a comprehensive set of econometric notes, no advice on theory is intended. Although originally intended to accompany an econometrics course in UCD, the following may be of interest to anyone getting started with Stata. Topics covered fall under the following areas: data management, graphing, regression analysis, binary regression, ordered and multinomial regression, time series and panel data. Stata commands are shown in red. It is assumed the reader is using version 11, although this is generally not necessary to follow the commands.
1 Introduction
Stata 11 is available on UCD computers by clicking on the “Networked Applications”. Select the “Mathe- matics and Statistics” folder and Stata v11. It is also possible to run Stata from your own computer. Log into UCD connect and click “Software for U” on the main page. You will first need to download and install the client software, then you will be able to access Stata 11, again in the “Mathematics and Statistics” folder. For further details see http://www.ucd.ie/itservices/teachinglearningit/applications/softwareforu/d.en. Stata 11 is recommended, however Stata 8.0 may also be available on the NAL (Novell Application Launcher). Click Start and open the NAL. Open the Specialist Applications folder and click into Economics. Open wsestata.exe, or right-click and add as a shortcut to your desktop. Alternatively, click Start > Run, paste in Y:\nalapps\W95\STATASE\v8.0 and click enter.
Before starting, we need to cover a very important principle of data analysis. It is vital that you keep track of any changes you make to data. There is nothing worse than not knowing how you arrived at a particular result, or accidentally making a silly mistake and then saving your data. This can lead to completely incorrect conclusions. For example you might confuse your values for male and female and conclude that men are more at risk of certain outcomes, etc. These mistakes are embarrassing at best, and career threatening at worst. There are three simple tips to avoid these problems. Firstly keep a log of everything. Secondly, to ensure you don’t embed any mistakes you’ve made in future work, most econometricians never save their datasets. Generally people initially react badly to this suggestion. However you don’t need to saves changes to the dataset itself if you implement all manipulations using do files. The final tip therefore, is to use do files. We will cover each of these in what follows. The first thing we need to do is open our data. If we have a file saved somewhere on our hard disk we could use the menus to load it. FILE, OPEN. Or we could write out the full path for the file, e.g. “h:\Desktop\”. The path for your desktop will differ depending on the computer your are using, however, if you are on a UCD machine this should be it. This is awkward, and we will also need somewhere to store results, and analysis. So we will create a new folder on our desktop called “Stata”. Right click on your desktop, and select NEW, FOLDER. Rename this to “Stata”. We will also create a new folder within this called “Ado” which we will use to install new commands. Save the files for this class into the “Stata” folder. Stata starts with a default working directory, but it is well hidden and not very convenient, so we want to change the working directory to our new folder. First we check the current working directory with pwd. Now we can change it cd ‘‘h:\Desktop\Stata’’. If you are unsure where your new “Stata” folder is, right click on it and go to PROPERTIES. You will see the path under LOCATION. Add “\Stata ” to this. Now we can load our data files. One final piece of housekeeping, because we can only write to the personal drive (“h:\”) on UCD computers we need to be able to install user written commands here. So we set this folder with sysdir set PLUS ‘‘h:\Desktop\Stata\Ado’’. This is only necessary if you are running Stata from a UCD computer. Now we have this set up, accessing files saved in Stata format (.dta) is straightforward. use icecream2. If you make changes to the data, you will not be allowed to open another dataset without clearing Stata’s memory first. gen year=2010. We will encounter the gen command later. Now if we try and load the data again use icecream2 we get the error message “no; data in memory would be lost”. We need to use the command clear first, then we can reload the dataset use icecream2. Alternatively, using the clear option automatically drops the dataset in current use use icecream2, clear. This raises a very important point, we need to keep track of our analysis and our changes to the data. Never ever save changes to a dataset. If you have no record of what you have done not only will you get lost and not be able to reproduce your results, neither will anyone else. And you won’t be able to prove that you’re not just making things up. This is where do files come in. A do file (not to be confused with an ado file)^1 is simply a list of commands
(^1) This is a do file which contains a programme. Stata uses these to run most of its commands. This is also how we are able
(a) Place the original dataset in a separate folder (b) Make a backup of the dataset (c) Use .dta files for Stata use
Stata has an inbuilt help function. In fact you can easily access the help file for any command. Suppose we are interested in the “tabstat” command, we can type help tabstat. However these are often aimed at experienced users and you may have difficulty understanding them. The syntax for this command is given as “tabstat varlist [if] [in] [weight] [, options]”. Items in square brackets are optional. So all we require to run this command is the command itself followed by at least one variable. The various options are explained, followed by some examples. Looking at the examples is often the best way of getting to grips with how a command works. If you cannot solve the problem using the help file, Stata has an extensive online support system. It is more than likely that someone else has encountered the same problem. A google search usually throws up sev- eral items of interest. There are also several excellent websites which detail how to deal with various aspects of data analysis. The best of these are the UCLA (http://www.ats.ucla.edu/stat/stata/sk/default.htm) and Princeton (http://dss.princeton.edu/online help/stats packages/stata/stata.htm) Stata websites. We are now ready to begin analysing our data.
We have already seen that importing data in Stata format (.dta files) is simple. The command is “use filename”. We need to load the icecream dataset for this analysis. use icecream.
Note: We’re opening a dataset. Remember, do not save any changes you make.
Often you will have to make do with Microsoft Excel (.xls) files. Fortunately Stata can import these quite easily. If you have an Excel file named myfile.xls, you can import it using Stata’s insheet command. First, in Microsoft Excel, click File > Save As. Now instead of saving as a Microsoft Office Excel file, save the file as a CSV (Comma Delimited) file using the dropdown menu. You can then load the data using the command insheet using myfile.csv. The “infile” command is an alternative for loading other types of data. If a direct import with this command fails, try opening it in excel and following the instructions above. We will discuss how to import SPSS files when discussing an example of a user written command.
One of the major advantages of Stata is the manner in which users can write their own commands. In the unlikely event that you are trying to do something that doesn’t have an official command, you are practically guaranteed that someone else has had the same problem, and can be reasonably confident that someone has written their own code to deal with the issue. Finding the answer to your particular problem is not always straightforward, but it can be as easy as a google search. Knowing exactly what to look for can be the main problem. If you can find the name of your programme it can be relatively straightforward to install. Later we will encounter two other user written commands (“tabout” and “catplot”), now we will consider the
programme “usespss” which is used to import data saved in SPSS format.^3. If we try to import the SPSS file in our directory, use spssfile.sav we get the error message “file SPSSfile.sav not Stata format”. You would imagine that it should be relatively easy to transfer files between different statistics packages but this is not the case. Without this command you might need to use the expensive StatTransfer programme. As we know what we’re looking for, the process of installing the programme is easy. We use the “findit” command. findit usespss. In fact if you’re sure of the name you can simply type ssc install usespss. If you are not exactly sure of the name, but have a general idea of what it’s called you can use the command search usespss, all. A new window will appear, and clicking on the blue link will take you to a new page. Click on CLICK HERE to install. This programme is now ready to run. You can also access the help file, help usespss. We can now open the SPSS file in our folder. usespss using spssfile.sav. We could now save this in Stata format for future use. save, replace. It is saved as “SPSSfile.dta”. However as you can see, this is just the same as our icecream dataset.^4 We will re-load the Stata version. use icecream2, clear.
Across the top of the Stata programme are a number of menus, and you may be tempted to use these to carry out your analysis. For example, going to ‘FILE’, ‘OPEN’, and selecting your file will open the dataset. As we will explain later on, this is not ideal. Not only is it slow, but it makes reproducing your results very tricky. The alternative is to type commands directly into the command window, which requires becoming familiar with the language of Stata, but is ultimately much more efficient and reliable. One benefit of using the menus is that when you run a command this way, it appears in the main window, which is where results of analysis are displayed. So this is a useful way to learn commands if you are unsure of them. Copying this from the main window into the command window and pressing enter will reproduce the command. This is in fact how to keep track of your analysis, by recording every change you make to the data. The Review window provides you with a list of all entered commands. Clicking on a command in the review window will cause it to appear in the command window. Failed commands are shown in red. The variable window gives a list of all the variables in the dataset, their labels, and their attributes.
Stata holds the data in memory like an excel file. To see the actual data select ‘DATA’ then ‘DATA BROWSER’ from the menus. You will see the variables ordered horizontally with the observations ordered vertically. Selecting ‘DATA EDITOR’ instead provides you with the same view, except you are now able to edit the data, like you would a spreadsheet. In fact this is an alternative way of entering data, you can simply paste it in. As before this is not recommended for reasons of reproducibility. Clicking on a particular case gives you the exact entry for that particular variable and observation. The data editor and browser windows must be closed before you can enter any new commands into Stata.
Getting to grips with how to communicate with Stata is perhaps the most daunting aspect of starting out. Generally programmes and commands take the form of “command name” “variable name(s)” “, options.” We will shortly see examples with tab and later regress. The exact syntax for a particular command is detailed in the help file. For example, help tab. Here the aim is to introduce you to some of the most important commands. As you become more familiar with them you will be able to use the various options available, depending on the particular task you wish to perform. Stata understands abbreviations, once the abbreviation can only be interpreted one way. For example, the full command to run a regression is “regress”, however Stata understands what you mean if you only type “reg”. The same principle applies to variable names. Using the icecream dataset, typing tab ti is equivalent
(^3) SPSS is a statistics package popular in the other social sciences (^4) An alternative for transferring SPSS files into Stata is to download SPSS which is available from UCD Connect, open the SPSS file and save in Stata format.
2 Data Manipulation
Here we introduce the basic commands for manipulating your data. The most important logical operators in Stata are outlined in table 1. The most frequently used are & (and), | (or) and! (not). These are essential for manipulating the data correctly. We can illustrate some of these using the “display” command, which we can shorten to “di”: di 10*20 and di 6/(5-2) +18. Notice that strings require double quotes di Welcome does not work but di ‘‘Welcome’’ does. You can also access system values and programme results with this command, for example today’s date di ‘‘‘c(current date)’’’. Note again that di ‘c(current date)’ returns an error message. We need single quotes because “c(current date)” is a macro. This is how we were able to name our log file, see section 2.10 for more details on macros. We will explain the use of the wildcard in section 2.9. Stata will know whether you mean multiplication or the wildcard depending on the situation.
Stata provides several ways of investigating and describing data. It is generally a good idea to browse the data once you have it loaded. This allows you to view the data in spreadsheet format. For a broader look at the variables in the dataset, use the sum command, which summarises all the variables. Alternatively, specifying a variable after the command (e.g. sum price) will summarize the price variable on its own. If you would like more precise information (e.g. percentiles) then you can add the detail option to the end of that command, i.e. summ price, detail. A very useful command is inspect. This summarizes a variable’s missing values (if any) and provides a simple plot of the variable’s distribution. Sometimes you may wish to break down summaries by a particular variable. For example, you might like to see how some variable changes over time. The bysort command is very useful here. It is best explained with an example. Suppose you want to see how consumption changes as temperature changes. The command here would be: bysort temp: summ cons. This means, in English, “summarize consumption for every distinct value of temperature.” Other variables that you may use again include describe and list. To investigate basic correlations, use the corr command followed by the variables you want to correlate. For example, corr price temp cons will provide a matrix of Pearson correlation coefficients between price, temperature and consumption. You may want to use the pwcorr command instead. It is essentially the same as corr but it allows for a little bit more detail. If you type pwcorr temp cons, sig it will provide p-values of the test with the null of the correlation being zero.
You will regularly have to generate variables to aid econometric analysis. For example, you may want to create dummy variables or run log-log regressions. To create a variable named loggedprice equal to the natural log of price, the command is gen loggedprice = ln(price). Similarly, to generate a variable equal to twice the square root of temperature, use the command gen twice root temp = 2 ∗sqrt(temp). Note that variable names cannot contain spaces. The egen (“extended gen”) command works just like gen but with extra options. For example, egen avg price = mean(price). With egen we can also break commands down into percentiles very eas- ily. For example, to create a variable equal to the 99th percentile of price, enter egen high price = pctile(price), p(99). Changing the 99 to 50 in that command would produce a variable equal to the median price. “egen” is often used to obtain a breakdown of a particular statistic by another variable. For example, we could obtain a variable containing the minimum income value for that particular province egen minincome=min(income), by(var7).
Oftentimes we want Stata to run a command conditional on some requirement. For example, the correlation between price and consumption if the temperature is greater than 25◦C. This is easily achieved: corr price cons if temp> 25. To add more conditions to a command, for example to examine the correlation
if temperature is both greater than 25◦C and less than 35◦C, we use the & operator: corr price cons if temp>25 & temp< 35. We can also use if to investigate data more closely: summ cons if price >.275. We can create dummy variables with if commands. Typically two steps are needed. First we create a variable set equal to zeros: gen expensive = 0. Now we replace it: replace expensive = 1 if price >avg price. See the tutorial on regression analysis for more details on dummy variables. Similarly we can control for outliers using if commands. For example if you want to eliminate the most expensive 5% of observations, the following would work:
egen top_fivepercent_prices = pctile(price), p(95) drop if price > top_fivepercent_prices
We remove these variables from the data with the “drop” command^5 as we do not need them in this analysis. drop loggedprice twice root temp avg price high price expensive.
One of the first things you will want to do with your data is to summarise its main features. Crosstabs are a useful pre-regression tool, and are also useful for presenting the main points of your data succinctly. The two most important commands for this are “tab” and “tabstat”. “Tab” tells you how many times each answer is given in response to a particular variable. This is only suitable for variables with relatively few entries, such as categorical data. If you try to use “tab” on a variable which has hundreds of different entries you will get an error message. Typing tab var7 will show the how many entries there are for each province. As with all commands, it can also be accessed through the menus via: STATISTICS, SUMMARIES, TABLES. It is also easy to obtain crosstabs which give a breakdown of a variable by another. For example typing tab var weekend will show how many weekend and weekday entries there are for each province. It is often useful to know the percentages as well as the actual numbers. We need to add an option to our “tab” command. tab var7 weekend, col will give us the percentage with each column. Typing tab var7 weekend, row will give us the percentage within each row. The second command which is useful here is “tabstat”. This is used for continuous variables, and its main use is to provide mean values. For example tabstat price will give the average price in the dataset. Using the command options we can also access other useful statistics such as the median tabstat price, stats(med), or the variance tabstat price, stats(var). For a full list of the available statistics, type help tabstat. As before we can obtain these statistics according to different levels of a second variable. tabstat price, by(var7) gives the average price for each province.
Labels are designed to help the user of a dataset understand and present their findings. These are often essential, for example if you have a categorical variable gender with two values 1 and 2, and no label you are in trouble as you will not know which refers to male and which to female. Generally these will be provided in your data, but not necessarily. Often the variable name itself will be self explanatory, for example in the icecream dataset the meaning of the variable “income” is obvious, although we do not know the unit it is measured in. It is not so obvious for var7, but a look at descriptives or the data browser makes it clear that it refers to Irish provinces. It is easy to rename a variable. Type rename var7 province into the command window. As well as their actual names, you can also label a variable. These can be used to provide additional information that is not apparent from the variable name. So far none of the variables in the dataset have these. Adding a variable label to a variable is also straightforward. Type label variable temp ‘‘Temperature Degrees C’’ and label variable cons ‘‘The number of ice-creams purchased.’’. You can see the
(^5) We can also select the variables we wish to remain in the data, with the “keep” command.
the master dataset, the dataset we merged with , or both. See help merge for details. For no we will drop this variable with drop merge.
We have already discussed tabulating variables and looking at crosstabs. Here we will examine how to extract these results in a way that can be easily used in presentations or papers. To do this we need the user written command “tabout”. To find and install, we first search for it. search tabout, all. The option all allows us to search the internet. We find an entry in blue for tabout, with the description: ‘TABOUT’: module to export publication quality cross-tabulations / tabout is a table building program for oneway and twoway / tables of frequencies and percentages, and for summary tables. It / produces publication quality tables for export to a text file.
2.7.1 Tabout with Stata 9/10/
You can install tabout from this link, or else by typing ssc install tabout. As before, there are essentially two cases involved, one analogous to “tab”, and the other analogous to “tabstat”. tabout county using filename.xls, replace gives us an excel table with the numbers in each county. The replace option is important (and an option which is available in most programmes which involve exporting results) and tells Stata to overwrite the file if it already exists. The alternative is append, which tells Stata to add new results to the same file. If we want percentages as well as numbers in each category we can use the following option: tabout county using filename.xls, append cells(freq co). We may also want to display crosstabs which we can do by adding a second variable, for example tabout county province using filename.xls, append. If we want percentages as well as numbers we can use the following: tabout county province using filename.xls, append cells(freq co). “Tabout” only works with variables which have labels, as these kind of tables do not really make sense for continuous variables such as income. However, we can make tables of means (or other statistics) like with “tabstat”. tabout province using filename.xls, append cells(mean income) sum gives us the average income for each province.
2.7.2 Tabout with Stata 8
Clicking on the link after running search tabout, all will open a page which allows you to install the pro- gramme. You will notice that Stata version 9 is required. We need a version which is compatible with the verision of Stata we are running. Here we need “tabout8”, but a search is unsuccessful. search tabout8, all. We will need to install it ourselves. If we google “tabout8” we will find the website “http://www.ianwatson.com.au/stata.html” as the first entry. Here we find a link to the .ado file, which we download and save in our personal directory which we can locate with the command sysdir. We also save the corresponding help file in this directory. This may seem like a lot of effort, however this only needs to be done once, and will save you a lot of time if you are handling datasets with large numbers of variables. It is possible to copy and paste from the Stata window into excel after using the “tab command”, but this is a painstaking process, especially if you are constantly updating your analysis. “Tabout” automates this process. If we want percentages as well as numbers in each category we can use the following option: tabout county using filename.xls, append cells(fcount fper). We may also want to display crosstabs which we can do by adding a second variable, for example tabout8 county province using filename.xls, append. If we want percentages as well as numbers we can use the following: tabout8 county province using filename.xls, append cells(double). “Tabout8” only works with variables which have labels, as these kind of tables do not really make sense for continuous variables such as income. However, we can make tables of means (or other statistics) like with “tabstat”. tabout8 province using filename.xls, append cells(mean income) gives us the average income for each province.
Table 2: Tabout Example 1 - Crosstabs Province Ulster Dublin Munster Connacht Total Weekend Num % Num % Num % Num % Num % Weekend 5 55.6 7 58.3 3 60.0 3 50.0 18 56. Weekday 4 44.4 5 41.7 2 40.0 3 50.0 14 43. Total 9 100.0 12 100.0 5 100.0 6 100.0 32 100.
Table 3: Tabout Example 2 - Variable Averages Mean Income By Weekend Weekend 84 Weekday 85 Total 85 By Province Ulster 83 Dublin 85 Munster 85 Connacht 86 Total 85
“Tabout” is at its most powerful when used in conjunction with LATEX, which is the software which was used to create this document. Note that the more recent version has a slightly different syntax, but the general idea is the same. You can also get confidence intervals using the latest version.
Sometimes we may need to recode particular values in order to carry out our analysis. For example we have information on all four provinces, but we may only be interested in comparing Ulster to the other provinces. We will generate a new variable province2, which at first is exactly the same as our province variable. gen province2=province. Now we will recode the Ulster value to be equal to one, and the other provinces to be equal to zero. In case we’ve forgotten, codebook province and then lablebook province1 will tell us the value labels. Ulster is already coded as 1, so we leave that as it is. There’s more than one way to change the value for the other countries. We could use the replace command. Either of the following would do the job: replace province2=0 if province> 1 or replace province2=0 if province2!=1 or replace province2=0 if province2==2 | province2==3 | province2==4. The recode command often accomplishes the same task with less effort. recode province2 (2/4=0). The “/” tells Stata to recode values 2 through 4 to be equal to 0.^7 “Recode” is also important if you want to change values within a variable simultaneously. For example suppose we want to reverse the coding on the variable “province”, we could do so with recode province (1=4)(2=3)(3=2)(4=1). This would not be possible using the “replace” command. If you do this, don’t forget to change the value labels. Now if we tab province2 we see only two values as required. To be sure that we’re not confused when we come back to the data later, or someone else is using it, we should label this new variable properly. We define a new label, lab def prov 0’’Leinster Munster or Connacht’’ 1’’Ulster’’. Then attach this to the variable province2. label values province2 prov2. Now tab province2 is self explanatory.
(^7) An even quicker command would be gen province2=(province==1).
macro with the “local” command, and access it using single quotation marks ‘’.^89 First we define a macro x which takes the numerical value 10. local x 10. Now every time we call the macro ‘x’ we have the value
forvalues i=1(1)24 { replace hour=hour*100 if hour==‘i’ }
Notice the syntax, we are creating a macro “i” which will start at the value 1, execute the command for that value, move on to the next value (“2”), execute the command for that value etc until the loop ends. The first number refers to the starting value, the number in brackets is the increment, and the final number is the end value. We need a curly brace at the end of this line, the command on a separate line, and another curly brace again on a separate line. Executing this command will give us a well behaved variable with every entry in the same format. sum hour. The other type of loop (the “foreach” command) is generally used when you want to perform the same task on a number of different variables. We will write our own programme to transform every variable into a z score. We will call it “zscore”. We then use the foreach loop, with “i” being the macro that corresponds to
(^8) Note that ‘ is the inward pointing single quotation mark, and is usually the button to the left of the number 1 on your keyboard. You may need to press it twice. (^9) There are also “global” macros which are rarely used. (^10) This is what we are doing at the beginning of our do file. Stata is told to access the date, and open a log file under that name. (^11) Type mac list to see which macros are currently in use. (^12) For more on accessing macros see help extended fcn.
every individual variable we wish to transform. The macro “0” refers to the list of variables we are interested in, essentially everything we type after our new command.^13 Like forvalues, we need a curly brace at the end of this line, and each of our commands also on a separate line. For every variable in “0” (our variable list) we are running the sum command, obtaining the macros for the mean and standard deviation, and then generating a new variable which will have the prefix “zscore”. We also summarise this new variable. After the final curly brace we need “end” to tell Stata the programme is finished.
capture program drop zscore program define zscore foreach i in ‘0’ { sum ‘i’ local m=r(mean) local n=r(sd) gen zscore‘i’=(‘m’-‘i’)/‘n’ sum zscore‘i’ } end
We can now run the programme on whichever variables we are interested in. For example, zscore time cons price. The summary statistics confirm we have what we wanted. Note that if you try to call a new programme by the same name as an existing programme you get an error message. program define zscore. So if you want to modify an existing programme you will first need to drop it. program drop zscore. But if there is no program called zscore this will produce an error message. Hence the use of “capture” just like when we were opening our log file. Also, you will need to define your programme again each time you start a new Stata session, unless you save it as an ado file.^14
It is possible to access individual observations with your data using subscripts. This takes the form of square brackets containing the observation number after the variable of interest. For example, di time[2] displays the value of the time variable for the second observation. This can be very important if you want to access information in the responses of other observations. For example you may have data on households and may want to use information provided by parents to analysis the outcomes of children. We will illustrate this with our province variable. Two special cases of subscripts are n and N. The latter is used to count the total number in each case. For example, gen totalno= N gives us a new variable which is the total number of observations in the dataset. It is obviously the same for each observation. tab totalno. On the other hand, gen totalno2= n tells us the ranking of each observation in the dataset, and runs from 1 to 32. tab totalno2. These are most useful when used with the by command. We will generate two variables which gives us the total number in each province, and also the rank of each observation in each province. First we need to sort our data sort province. Then by province: gen provinceno= N^15 and bysort province: gen provinceno2= n. We can use the data browser to confirm that this generated the variables we expected. In this case we have some province level data in var10, however it is only present for one observation in each province, and we need it in all observations. This is a case where you may be tempted to use excel, but apart from the replication issue, this will simply not be possible if you have a datatset with 1000s of observations and hundreds of variables. Instead we can use subscripts and a loop to make the change:
forvalues i=1(1)10 { by province: replace var10=var10[‘i’] if var10==. & var10[‘i’]!=.}
(^13) Within the macro “0”, the macro “1” refers to the first variable, “2” the second etc. (^14) It so happens that Stata already has a way of creating standardised variables with egen newvar=std(var). (^15) These two steps could be combined with “bysort”: bysort province: gen provinceno= N
Figure 1: An example of a graph matrix chart
cons
temp
price
.
.
.
.2 .4.
20
40
60
80
20 40 60 80
.
.
.
.
.26 .27 .28.
We can save any graph we produce in Stata using the graph export command. After drawing our graph, Stata will open it in a new window. It is possible to save it using the menus FILE, SAVE AS. We can also type graph export filename.png, replace. Stata can save graphs in various different formats, but .png is the most straightforward. 18. We can then use the graphs in other documents and presentations.^19 It would take too long to go through all of the available options, but some of the most important ones refer to the title and axis labels. For example:
line income temp time, title(Time Series Graph of Income and Tempreature Over Time) /// xtitle(Time Period) ytitle(Euro(Income) and Degrees(Temp)) caption(Source: icecream.dta)
(^18) .wmf is best for word documents, .eps is best for LATEX. (^19) There is a useful graph editor available in Stata version 10 onwards.
The “///” tells Stata to read the next line as part of the same command. Two examples of the kind of graphs that are possible are provided below. The first graph was made using the user written command “spmap”. The second graph was generated using the cyear dataset with the following code:
twoway(scatter gdppc u5m if gdppc<1000 & year==2005, mlabel(country2) mlabsize(tiny)) /// (lfit gdppc u5m if gdppc<1000 & year==2005), /// caption(’’Source: WHO and Penn World Tables’’, size(tiny) span) legend(order(2 ’’Linear Fit’’)) /// title(’’National Income Per Head and Under 5 Mortality’’, span) /// ytitle(’’GDP Per Capita in US Dollars’’, size(small)) note(’’Note: Correlation=-0.1737’’) /// plotregion(style(none)) legend(pos(4) col(1)) /// xtitle(’’Under 5 Mortality, Deaths Per 1,000 Births’’) /// graphr(lwidth(thin) ilwidth(vvthin) ilcolor(black) ilpattern(solid)) /// subtitle(’’Developing Countries in 2005’’, span)
For more examples see: http://www.survey-design.com.au/Usergraphs.html
And: http://www.ats.ucla.edu/stat/stata/library/GraphExamples/default.htm