Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Stata Commands Cheat Sheet, Cheat Sheet of Introduction to Econometrics

Cheat sheet on data processing, data transformation, data visualization, plotting, data analysis and programming with stata 15

Typology: Cheat Sheet

2020/2021
On special offer
30 Points
Discount

Limited-time offer


Uploaded on 04/27/2021

michaelporter
michaelporter 🇺🇸

4.5

(24)

52 documents

Partial preview of the text

Download Stata Commands Cheat Sheet and more Cheat Sheet Introduction to Econometrics in PDF only on Docsity! Data Processing with Stata 15 Cheat Sheet For more info see Stata's referenc.e manual (stata.com) F2 - 121� -" � Jttons describe data Ctrl + 8 Ctrl + 9 open a new .do file Ctrl + D open the data editor clear delete data in memory highlight text in .do file, then ctrl + d executes it in the command line rll = � t4A�0 D P PgUp PgDn serali through previous commands Tab autocompletes vanable name after typing part cls clear the console (where results are displayed) pwdl print current (working) directory cd "C\Program Files (x86)\Stata13" change working directory dir di splay filenames in working d irectory dir".dta List all Stata data in working directory .cauture log close---------t close the log on any existing do files log using "myDoFile.txr, replace create a new log file to record your work and results search mdesc 1 _ ,, find the package mdesc to mstall ra e :I'--nands that ssc i nstall mdesc �- �o install the package mdesc; needs to be done once lmp9rt:pat sysuse auto, clear } fo ma exarrpes reload system data (Auto data) u,e ttie auto dataset use ·yourStataFile.dta ·, clear load a dataset from the current directory . ed import excel ·yourSpreadsheetxlsx·, r-·. •; sheet("Shee,1") cellrange(A2:H11) firstrow import an Excel spreadsheet import delimited "yourFile.csv·, /* "/ rowrange(Z:11) colrange(1 :8) varnames(Z) import a .csv file web use set ·olll)S://githl,1><lC>ff'/G�ntortstmrr.,,nog1raw/ma:ter/OayZJO•,.,· webuse "wb_indicators_long· set web-based directory and load data from the web Basic Syntax Ali Stata commands have the same fermat (syntax): [by varlist1:] commond [varlist2] [ =exp] [if exp] [in range) [weight] [using filename] Loptions] ._________, �--� ._________. �-do --- -. '-- command • e :nplE- Yt'E "'i1r.:: • on ed ,... __ vrrist1 bysort rep78. s ummarize price if foreign == O & price <= 9000, deta:I " wc _. � oh.. ,,..'":i a-d �a To find out more about any command - like what options it takes - type hel p command Arithmetic add (numbers) & + combine (strings) and ! or- not or ! =] not -Cli'= equa! < less than ual 'lhle < = less than or equa! to > greater than - subtract " multiply if fo<eign !� 1 & price : 10000 > = greater or equa I to rf fore�n 1: 1 ( pnce : 10000 / divide " " raise to a power Ex lare Data _g_escribe make price display variable type, fermat. and any value/variable labels count count if price > 5000 number of rows (observations) Can be combined wIth logie ds, has(type string) lookfor '1n.· search far variable types. vanable name. or variable label isid mpg check if mpg un1quely identifies the data codebook make price overv1ew of vanable type, stats. number of missing/unique values summarize make price mpg print summary statistics (mean. stdev. min. max) far variables inspect mpg show histogram of data. number of missing or zero observations histogram mpg, freguency �plot a histogram of the distribution of a variable IN_THl [ browse or Ctrl + 8 open the data editor ng e �---- - ,,u bo/ - € !ist make pnce if price > 10000 & tmissing(pnce) gist .. 1co'T1pact formJ list the make and price far observations with price > $10,000 .display price[4] display the 4th observation in price; only works on single values gsort price mpg (a:.cend r,g) gsort -price -mpg (de$Cendingl sort in arder. first by price then miles per gallon duplicates report assert price!=. finds ali duplicate values in each variable verify trum of claim levelsof rep78 display the uruque values far rep78 �� ·��r'.i%l•r:-� ._ Stata has 6 data types, and data can also be missing: ru2..da!a tme/false WQ!ds .r:ll..l!Ilbill m1ssmg byte string int long float double To convert between numbers & strings: gen foreign'String = string(foreigo) tostring foreign, gen(foretgnStnng) .d.ecode foreign. gen(forégnString) ·1· ·1· "foreign' gen or<? g-, ,L,..,e - = real(fore g�" "';, ì" destrlng fo '? gnStr !'19. gen(fo '? gnNums" .. J ·1• encode 'c"t ':i,: '::i gen(fc,,, gnNum,; ._) "foreign" recast double mpg generic way to convert between types � " 7nacie fo, � rep7.:. � [ uC - • • b - n:,p,;; �rrl 1.abul ate rep 78, mi 1ge n(repairRecord)1 one-way table: number of rows with each value of rep78 tabulate rep78 foreign, mi two-way table: cross-tabulate number of observations tor each combination of rep78 and foreign _bys_ort rep78: tabulate foreign far each value of rep78, apply the command tabulate foreign tabstat price weight mpg, by(foreign) stat(mean sd n) create compact table of summary statistics - sia:s i = � ç, ���.--'---, table foreign, contents(mean price sd price) f(%9 Zfc) row create a flexible table of summary statistics collapse (mean) price (max) mpg, by(foreign)- ep .::e'?. c.;;-� calculate mean price & max mpg by car type (foreign) generate mpgSo = mpg"Z gen byte lowPr = price < 4000 create a new variable. Useful also tor creating binary variables based on a condition (generate byte) generate id = _n bysort rep78: gen repairldx = _n _n creates a running index of observations in a group generate totRows = _N bysort rep78: gen repairTot = _N _N aeates a running count of the total observations per group pctile mpgQuartile = mpg, nq = 4 create quartiles of the mpg data egen meanPrice = mean(price), by(foreign) - help egen calculate mean price far each group in forergn � rrore opoo-,s updated June 2016 � Data Transformation with Stata 15 Cheat Sheet For more info see Stata's reference manual (stata.com) Select Parts of Data {Subsetting) :;ELE -- '.:' E . C (OLUMNS drop make remove the 'make' variable keep make price apposite of drop; keep only variables 'make' and 'price' r TE'"' SPE - F C. t l, • <; drop if mpg < 20 drop in 1/4 drop observations based on a condi tìon 0eft) or rows 1-4 (right) keep i n 1/30 apposite of drop; keep only rows 1-30 keep if inrange(price, 5000, 10000) keep values of price between $5.000 - $10.000 CTnclusive) keep if inlist(make, "Honda Accord", "Honda Civic·. ·subaru") keep the specified values of make sample 25 sample 25% of the observations in the dataset (use set seed # command tor reproducible sampling) Cl!ANG[ (OLUMN NAM[S .ren.ame (rep78 foreigin) (repairRecord carType) rename one or multiple variables CHt �E R V VAL lb replace price = 5000 if price < 5000 replace alt values of price that are less than $5,000 with 5000 recode price (O/ 5000 = 5000) change all prices less than 5000 to be $5,000 recode foreign (O= 2 "US")(1 = 1 'Not US"), gen(foreign2) change the values and value labels then store in a new variable. foreign2 EP '-" E ,/'I .. , G IALUt:, mvdecode alt, mv(9999) " 1 .. , " "'' replace the number 9999 with missìng value in alt variables mvencode _ali, mv(9999) "" ., • e � _ replace missing values with the number 9999 for alt variables Value labels map string descriptions to numbers. They allow the underlying data to be numeric (making logica! tests simpler) while also connecting the values to human-understandable text .l.s!.bel define mylabel O ·us· 1 "Not US • label .ltalues foreign mylabel define a label and apply it the values in foreign label !ist list alt labels with1n the dataset note: data note here piace note m dataset Reshape Data webuse set https //g,thub.corn/GeoCerner/StataTra rt'lg/raw/mast.erfJay2/Data webuse ·co�eeMaize.dta" load demo dataser MELT DATA (WIDE - LONG) re•hape var ables start ng un qtF. !1 create: 'lE , var Jble wh eh captu�s "! E' � "rat : •'ie r':; r •� (C -- -.,....,..é, reshape long coffee@ maìze@, i(country) j(year)- new variable convert a wide dataset to long TIOY DATASETS W10E m elt cast LoNG (Tiov) have each obser- . .,, ,.,.... -, •• -- vation in ìts own row and each varìable in ìts own CAST DATA (LONG - WIDE) When datasets are tìdy, they have a c o n s i s t e nr. standard fermat that is easier iO manipufate and analyze. what v. be create riew vara Dite create: 'll='o\ va iables n,:irned un que d wTth the year adae,co"ee-01 mace2U'::. "var ab1€ (key to the co:urnn arn.. � r1r reshape wide -..,e,. ::.'\ 1(rnur·ry ) j(year) convert a long dataser to wide L xpose, clear vamame transpose rows and columns of data, cfearing the data and saving old column names as a new variable called ·_varname· ADDING (APPENDING) NEW DATA webuse coffeeMa ze2 dta, clear save coffeeMa1ze2 dta, re piace load oemo data webuse coffee! ia ze.dra, clear fillpend using ·coffeeMaize2.dta", gen(filenum) add observations from ·coffeeMaize2.dta" to current data and create variable "filenum· to tracie the orìgin of each observation Mi:RGING Two DA A [ T GE -Ef< MA- webuse nd age.dta, clear save 1nd_age.dta, replace webuse ,-.a_ag dta, clear merge 1:1 id using 'ind_age.dta' one-to-one merge of "ind_age.dta· into the loaded dataset and create varìable • _merge· to track the orìgin webuse hh2 dta, clear save hh2 dta, replace webuse '12.d'a clear merge m:1 h1d using "hh2.dta· many-to-one merge of "hh2.dta· into the loaded dataset and create variable • _merge· to track the orìgin I Fuzz 1A~ .'-li I\.. -::c1•s I :; -�G D -A:,ET A -ye,u- A ·=-M • e rmmi, match recOfds from different data sets using probabilistic matching mt r � • create distance measure for similarity between two strings Manipulate Strings GET STRING PROPERTIE., display length("This string has 29 characters") retum the length of the string charlist make ,_,." P Jr. display the set of unique characters within a string display strpos("Stata·, ·a·) return the posit1on In Stata where a 1s first found �,Ne I 1ArH G .:=TRIN.:i� display strmatch("123.89', "1??.?9") retum true (1) or false (0) if string matches pattern display substr("Stata·. 3. 5) return string of 5 characters starting with position 3 list make if regexm(make, ·10-9)") list observatìons where make matches the regular expression (here, records that contain a number) list if regexm(make, "(Cad.jChev.!Datsun)") retum ali observations where make contains ·cad.". "Chev." or ·oatsun· !ist if inlist(word(make. 1), ·cad.", "Chev.", ·oatslin") retum ali observations where the first word of the make variable contains the listed words -KA, FoR� sT� r,,Gs display regexr("My string·, "My", "Your") re piace string1 (" My") with string2 ("Your") replace make = subinstr(make, ·cad.". "Cadillac·. 1) re piace first occurrence of ·cad." with Cadillac in the make variable display str itrim(" Too much Space") replace consecutive spaces with a single space display trim(' feadfng / traìling spaces ') remove extra spaces before and after a string display strlower("S TATA should not be ALL-CAPS") change stnng case; see also strupper. strp,roper display strtoname("War name") convert string to Stata-compatible variable name display real("100") convert string to a numenc or m1ssing value compress compress data m memory save ·myData.dta·. replace saveold ·myData.dta", replace verJion(12) save data in Stata fermat. replacing rhe data if a file with same name exists export excef ·myData.xls", l" •1 firstrow(variables) replace export data as an Excel file (.xls) with the variable names as the first row export delimited "myData.cw·, delimiter(", ") replace export data as a comma-delimited file (.csv) updated June 2016 .l:l:Jn'..A.Q Data Analysis with Stata 15 Cheat Sheet For more info see stata·s reference manual (stata.com) I' T Id· � ,�t Summarl·ze Data Examples useauto.dta (sysuseauto,dear) unless otherwlse noted univar price mpg, boxplot • ...: .• i... u calculate univariate summary. wrth box-and-whiskers plot stem mpg return stem-and-leaf display of mpg summarize price mpg, detail -1 , , catculate a variety of univariate summary statistics ci mean mpg price, level(99) - " 1r .....,1 r compute standard errors and confidence intervals correlate mpg price return correlation or covariance matrix pwcorr price mpg we1ght, gar(0 05) return all pairwise correlation coefficients wrth sig. levels r mean price mpgestimates of means. including standard errors proportion rep78 foreign estimates of proportions. including standard errors for r, catcgories idcntificd in varlistI ratio estimates of ratio, including standard errors l total priceestimates of totals. including standard errors Statistica! Tests tabulate foreign rep78, chi2 .e_xact_gmected tabulate foreign and repair record and retum chi2 and Fisher's exact statistic alongside the expected values ttest mpg, by(foreign) estimate t test on equality of means tor mpg by foreign ::: prtest foreign == O. 5 one-sample test of proportions ksmirnov mpg, by(foreign) g_xact Kolmogorov-Smimov equality-of-distributions test ranksum mpg, by(foreign) equality tests on unmatched data (independent samples) [ anova systolic drug -t>u 1- ' analysis of variance and covariance pwmean mpg, over(rep78) pveffects mcompare(tukey) l estimate pairwise comparisons of means wrth equal variances include multiple compartson adjustment Decla re Data By declarmg data type, you enable Stata to apply data mungcng and analys1s funct1ons specific to certam data types TIME SERIES -+. ... ,,. • tsset time, yearly Bm PANEL / LONGITUDINAL wdluse rlswori:. cle.ar declare sunspot data to be yearty time series HH3 tsreport report time series aspects of a dataset 9.enerate lag_spot = L 1.spot c 1_ reate a new variable,of annua! lags � �;,J.,..ts " ts ine spot · 1 • A • , • ft A e plot time series of sunspots ••, � arima spot, ar(1/2) I .., · estimate an auto-regressive model with 2 lags TtME SERIES 0PERATORS I xtset id year dedare national longitudinal data to be a panel t-t xtdescribe report pane! aspects of a dataset xtsum hours summarize hours worked. decomposing , � � standard deviation into between and within components xtline ln_wage if id <= 22, tlabel(#3} plot pane! data as a line plot o----- . - ---...,.,.. xtreg ln_w c.age##c.age ttl_exp, fe vce(robust) estimate a fixed-ef ects model with robust standard errors L llg x.- F. le.ad:x,., I.Z. 2-penoa rag •• , fZ. 2-i»riod lHd •..i SURVEY DATA O. �rencew,.-..,. S. SUSONI differeroce X .... , 02 -,_dd<Fe""'cel\.-.:,.,il',.,,U S2. lag-2 (seasonal o.fferfflce) r,-", UsEFUL Aoo-lNS ---------------- 1:scollap 00frf>,1Ct tn>@ series "1!D ,.....,,.., wm, and end-cl-p@riod valuo, canry(orward CMT)I non-rrming values ID<watd from one om. ID the next tsspell idffltify ,pe1, cx runs in tòne sorin SURVIVAL ANALYSIS stset studytime, failure(died) , declare survey design for a dataset stsum lii --+-- I summarize survival-time data e stcox drug agej estimate a Cox proportional hazard model o Estimate Models storesresult5asQ -dass iggress price mpg weight vce(robust) estimate ordinary least squares (OLS) model on mpg weight and foreign, apply robust standard errors iggress price mpg we1ght if foreign == O. vce(cluster rep78) regress price only on domestic cars, cluster standard errors rreg price mpg weight genwt(reg_wt) estimate robust regression to eliminate outliers probit foreign turn price. vce(!:obust} estimate probrt regression with robust standard errors ,!Qgitforeign headroom mpg, or estimate logistic regression and report odds ratios bootstrap, reps(100):.rggress mpg /* */ we,ght gear foreign AoomoNAL Moow pc.I - -•lblll � ...._..,. � l'KIOf ,,....,,...., ""'°'aNl,sk pob-•nllf"ll CIMI- - -,d- "'"9"" IZl) lnltn,�-lablo, m ..... ...ìm.n ...,.,,....,._l!!J..c;,..,..,.....,z,<9'....,,,d� -mm� .... .._ i§rèS❖·:i:dritl pr.,.a,1CCWe� l!lilll .,.-c:iomd ,....,. svyset psuid (pweight = finalwgt), strata(stratid) declare survey design for a dataset svydescribe report survey data details r svy: mean age, over(sex) I estimate a population mean tor each subpopulation svy, subpop(rural): mean age " estimate a population mean for rural areas I svy: tabulate sex heartatk report two-way table with tests of independence svy: reg zinc c.age##c.age ternale we1ght rural estimate a regression using survey weights tJ Diagnostics some ore tnappropriate w1th robust SEs estat hettest test for heteroskedasticity ovtest test tor omitted variable bias vif report variance inffation factor dfbeta(length) MJOn pfoc calculate measure of inffuence -"' � ._.,u. � - rvfplot, yline(0) e . ,. e •, avplots plot residuals li�li� plot ali partial- against fitted � t� regre�sion leverage values " . .;.,..,., _ plots m one graph I] Postestimation commands that use a fttted model _rg_gress price headroom length " ..... , .... "'"'"'" eum.,i,,, .Qisplay _b[length] display _se[length] return coefficient estimate or standard errar for mpg from most recent regression model ma rgins, dydx(length) ,. " ,. •.,,- u .- . vs .JSed estimate regression with bootstrapping jackknife r(mean), double: sum mpg jaddmife standard errar of sample mean ED --<>--o.-"""'""°"' return the estimated marginai effect for mpg Est i mation with Categorica I & Factor Varia bles more deta1ls at http://www.rtato.com/manuals/u25.pdf "' ma rgins, eyex(length) retum the estimated elasticity for price predict yhat if e(sample) (ONTJNUOUSVARIABL.ES R mea1ure something CATEGORICA!. VAR!ABLES ■ • • identify a group to whK:h an observabons belongs INDICATOR VARIABLES T F denote whethersomething is bue cr false O�ERATOR ib. Me1 c. o. � ,nr OESCRIPT10N specify ìndicalD,s specify bare indìcatll< a>mmand IO ct>ange ba!e treat variable as ccntiruous orrit il varìilbfe or indic:ator specify -· ,pecify lactorial Ìn11!fiKIÌ<ms ExAMPLE regress pnce Ln,p78 ,egress price ibC3).rep78 lvset baso flrl!quent rep 78 ,egress pnce Lfcre,gnlunpg 1Jcreign ,egreu price lo(Z)Jep78 ,eg,..n pria, mpg c.mpgltff1>9 ,egress pnce <Jll)Qtlc.mpg specify rep78 variallle ID be an Oldlc.nDr ·;ariable set lhe third ca.:egory or rep78 ID be lhe ba<e categery <et the ba;e IO most m,quently cxwmng Còl!gOry ror '"1)78 treat mpg as a a>nbn1JOU$ vMlab!e and tpecrfy an vn:eract:ion between forelgn and mpg ,et "'1)78 a, an.,éoca10r cmitob<ervation1 with rep78 == 2 create a iqua!Wd mpg tffm a, be used In regl"HSXln cnoate all pos<ible lnteraction1 ""h mpg (rrc,g and mpg'J create predictions tor sample on which model was fit predict double resid, residuals calculate residuals based on last fit model test headroom = O test linear hypotheses that headroom estimate equals zero lincom headroom - length test linear combination of estimates (headroom = length) updated June 2016 � Programming with Stata 15 Cheat Sheet For more rnfo see Stata's reference manual (stata.com) O Scalars both r-- and e--class resutts contain scalars scalar xl= 3 create a scalar xl storing the number 3 �ar a1 = ·1 am a string scalar· create a scalar a1 storing a string r; can hold numer,c val= or rtr.. ong ng,: fJ Matrices e--dass results are stored as matrices matrix a = ('1\ 5\ 6) J:::l matrix b = (J. 8. 9) [Il]create a 3 x 1 matrix t1 create a 1 x 3 matrix matrix d = b' transpose matrix b. store in d D:11-§ matrix ad1 = a \ d B § matrix ad2 = a, d l=l....!=l=l row bind matrices - column bind matricestfllll matselrc b x. c(1 3) � se!ect columns 1 & 3 of matrix b & store in new matrix x mat2txt, matrix (ad1) salling(textfile.txt) reulace export a matrix to a text file 0-- � DISPLAYING & DELETING 8UILDING BLOCKS (scalar I matrix I macro I estlmates] [!ist I drop] b list contents of objea b or drop {delete) object b (5c.alar I .matrix I m.auo I .e.stimates] dir list all defined objects for that class matrix !ist b matrix dir scalar drop x1 list contents of matrix b list ali matrices delete scalar x1 D Ma eros public or private variables storing text O GLOBALS avarlable th'OJgh S:a-:a sessrcns I\Jeuc _g!obal pathdata "C:/Users/SantasLJttleHelper/Stata" define a global variable called pathdata cd �pathdata - , change working directory by calling global macro _global myGlobal pnce mpg length summanze $myGlobal summarize price mpg length using global � LOCALS avarlable only rr p<nQram< loops or CIO file!" P,w,.� locai mylocal price mpg length create locai variable called mylocal with the strings price mpg and length summarize"mylocal' -� .... .,,."'u summarize contents of locai mylocal levelsof rep78, localOevels) create a sorted list of distinct values of rep78. stare results in a locai macro called levels locai varlab: variable J.g_bel foreign stare the variable label for foreign in the locai varlab 0 TEMPVARS & TEMPFILES 'oe<1<11 IO'.al5 !or oopstprogram� tempvar temp1 - •1.n • n.w toMc,o,i,-,-,. •blo a .ed•• • generate ·temp1' = mpgA2 - ..,,.. _ """1-'k. te,,,p summarize ·temp1' - _ -. � tempfile myAuto create a temporary file to ., • :.o save 'myAuto' be used within a program """pn,me R- ANO E-CLASS Stata stores calculation results in two· main classes: retum results from estJmalion sudi as summarize 01.tahulate commands such JS regress or mean To assign values to individuai variables use: SCALARS 7' individuai numbers or strings 2 MATRICES rectangular array of quantities or expressions 3 MACROS pointers thac stare text (global or locai) •tw-!!'iahcH••d 1<11� D Access & Save Stored r- and e-class Objects Many Stata cornmands store results 1n types of lists. b access these. use retum or eretum comrnands. Stored results can be scalars. macros. matrices °' functions. summarize price. detarl mean price retum list eretum list returns a list of scatars rerurns list of scalars. macros. matnces and funct1ons scailars: r(N) r(Man) r(Var) r(sd 74 616S.25 ... e(df_r) � 73 .,, e(N_Ol<er / • 1 E scal.ar,-: • 8699"5225.97... a:,mm:ar.c1 e(H) 7] 25149.49 . 11 e(k_eq) • l e(r•nll) • 1 9.enerate p_mean = r(mean) create a new variable equa I to average of price generate meanN = e(N) create a new vanable equal to obs. in estimation command preserve create a temporary copy of active dataframe restore restore temporary copy to point fast preserved ACCESSING ESTIMATION RESULTS I After you run any estimation corrvnand. the results of rhe estJmates are stored 1n a structure tha: you can save, view: compare. ano export @ress pnce v�gt,+ estimates store est1 sfare previous estimation results est1 in memory eststo est2: regress pnce v.eight mpg eststo est3: regress price weight mpg ioreign estimate two regressìon models and S1ore estimabon results �imates table est1 est2 est3 print a table of the two estimation results est1 and est2 EXPORTING RESULTS The esro. · and Lu· · 2 packages orovide numerous, fleJ<;b!e options lor malcing tab'es afte< est,mation command� See a·so putexcel and putdocx commands. esttab est1 est2. se star(• 0.10 ·• 0.05 • ·* O 01) labe create summary table with standard errors and labels esttab usìng ·auto_reg.txt", replace plam se export summary table to a text file, include standard errors outreg2 [est1 est2] using ·auto_reg2.txr, see replace export summary tabfe to a text file using outreg2 syntax Additional Programming Resources (") bit.ly/statacode download ali examples from this cheat sheet in a .do file U adoupdate adolist Update user--written .ado files List{copy user--written .ado files (") net install package, from (�/raNg.�=marr,e/repa,'master) install a package from a Github repository 9 https://g ithub.com/andrewheiss/SublimeStataEnhanced configure Sublime text for Stata 11--14 Loo s: Automate Re etitive Tasks ANATOMY OF A LOOP Stata has three options for repeating commands aver l ists or values: foreach, forvalues. and while. Though each has a different first lìne, the syntax is c.onsistent foreach x of varlist varl var2 var3 ie,qUD"n locai ffltlcro notation COl!llland � • , opt ion I comnw>djs) you wam to .-.peatan be one 1-,e or many FOREACH: REPEAT (OMMANDS OVER STRJNGS, ltSTS, OR VARIABLES foreach x inlof [ �al �al va1;.. �I!'� numi s; ( Stata commands refemng to ·:x t':-;iet ocec::: e7.e-• � C0ffl""' nd.� ��: .. } Snulifil foom: �peat ..,e- ::.am� crr.imarvJ foreach x in auto ata auto2 ci.a ( sysuse •auto.dta", e ear F ove•d"e=trgsmem: sysuse ""x'". clear tab rep78, ■issing tab rep78. miss1ng sysuse "auto2.dta", clear L } tab rep78, 111issing ISTS foreach x in ':Jr. Nick' "Dr. Hibbert' (]- display length("Or. Nick") display \ength ( • X • l display length("Or. Hibbert") L nen e• ,,g a ccr,maP"ICI U\lt :J M • ; VARIABU:S .. � ho ,,....K!'O ,..,.1-,..,._ t.: 'I' ...�•: foreach x in m� we ght ( summanze x , ____ _ ·IO<acllnlilce<,r,y"'1ili an Mgl.lT'lent. w.:h eloment<!-1)1' foreach x Qf vaf!ist mpg weight { summan=e x �o(-l""'1D<U!PÙ>el<ttype_ v;hdl rn.ue< li fo..er } ·1 FORVALUES: REPEAT (OMMANDS OVER ltSTS OF NUMBERS forvalues . � •oi10)SO [ ] � - '" g__splay · _,,,.. .,.. _, . uch rn� i:-.. � 1 1001>..., " lrrTERAmi,;:ro;:;:,.;R�s====il�- -� : 10,50 - ,o. tt ·1 � ·ono1so ,o. 20 . .o. DEBUGGING CODE dOlOtoSO 1-0 20. 30 set !!:ace on (off) e _ trace the execution of programs for error checking PUTTING 1T ALL TOGETHER generate car_maKe = word(make. 1 ) levelsof car_make, local(cmake) - local , = 1 locai cmake_len word count cmake' foreach x of local anake { display in ye,'r<m "Make group I is Y if == cmake_len' { display 'Tue tota! number of groups is "i'" } locai 1 = ++f - }- updated June 2016 .a:J!Y..,UI
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved