







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!








02/03/ Elena Esposito
Introduction Do-file is a text file containing commands → specific code to do something always identical to the data. STATA datasets have “.dta” extension Log file reproduce every output that appeared in the main face of the stata, the sum of everything; to create it it is necessary to type log using [name].log, to close the log file type log close.
COMMANDS
Introduction To import (.xls) data there are two ways: 1) Interactively: File - Import - Excel Spreadsheet
2) Manually: Import excel “users//pupibiancone/excel spain_data.xlsx, sheet("Series-layout A") firstrow. To import delimited(.csv) data → it can store a lot of data. NB Quando scriviamo import/use è buona norma mettere “, clear” in modo tale che con un unico comando rimuoviamo il dataset precedente e lo sostituiamo con il nuovo importato.
Problems that we could face when importing data:
To save the Data It is possible to use the command: save [file_name.dta] If the file already exists and we want to overwrite it we need to use the command: save [file_name.dta], replace
Logical Expressions & Mathematical Functions Logical expressions ● &: And ● |: Or ● !: Not ● >=: Larger or equal to ● <=: Smaller or equal to ● ==: Equal to ● !=: Not equal to Mathematical function ● Abs(x): Absolute Value ● Log(x): Natural Logarithm ● Sqrt(x): Square root ● Exp(x): Exponential
Generating new variables Generate [type] newvariablename = expression [if]
Grouping observations We often want to calculate statistics or variables at the group level:
Append command → Suppose you have two datasets with the same set (or subset) of variables. To combine them vertically, use Append → Observations from the second dataset are added below those of the first dataset (Append using …)
Combining datasets in Stata Combine two datasets with different information that share the same key variable. I.e. One dataset contains GDP and another contains population (key variable: country).
Merge command:
- 1:1 One-to-one merge: merge 1:1 varlist using filename.dta → each key value appears once in both datasets Example: one row per country in both datasets Esempio pratico: Hai un dataset con i dati del PIL dei paesi per il 2026 (una riga per paese: Italia, Francia, Spagna...) e vuoi unire un secondo dataset che contiene il tasso di disoccupazione sempre per lo stesso anno (una riga per paese).
- m:1 Many-to-one merge: merge m:1 varlist using filename.dta → many observations in the master dataset, one observation per key in the using dataset Example: individuals (many) merged with region-level data (one per region). Esempio pratico: Nel master dataset hai i dati di singoli individui (es. Mario Rossi, che vive in Piemonte; Luigi Bianchi, che vive in Piemonte; Anna Verdi, che vive in Lombardia). Nel secondo dataset hai dati generali sulle regioni (es. il numero di ospedali in Piemonte, in Lombardia...). Stata prenderà il dato del Piemonte e lo "incollerà" su tutte le righe degli individui che vivono in Piemonte. - 1:m One-to-many: merge 1:m varlist using filename.dta → one observation in the master dataset, many observations per key in the using dataset. Example: region-level dataset merged with individual-level dataset Explanation: this merges the dataset in memory with filename.dta using the key variables listed in the varlist. Esempio pratico: In memoria hai il dataset delle regioni (una riga per il Piemonte, una per la Lombardia) e vuoi unirci un dataset esterno che contiene i dati di tutti i singoli cittadini italiani (molti individui per ogni regione).
Quando esegui questo comando, Stata crea automaticamente una nuova variabile chiamata _merge. Questa variabile è utilissima perché ti dice per ogni riga se l'unione è andata a buon fine:
● _merge == 1 : L'osservazione era presente solo nel dataset in memoria (master). ● _merge == 2 : L'osservazione era presente solo nel dataset esterno (using). ● _merge == 3 : Match perfetto! L'osservazione è stata trovata in entrambi i dataset e i dati sono stati uniti con successo.
Di solito, subito dopo un merge, si usa il comando tab _merge per verificare quanti dati hanno trovato un corrispettivo nell'altro file.
Useful option include (id represent the specified variable):
Regression in Stata regress varlist [weight] [if exp][in range][,options]
Interpreting regression output
- Sample size: = Number of observations - Goodness of the fit: R-squared → the model explains the shares of the variation in Y explained by the model - Coefficient of interest: it is the slope of the fitted line - Statistical significance: It measures the probability of observing the result if the null hypothesis were true. P-value= 0.001 → The effect is statistically significant. This means: if the true effect were zero, the probability of observing an estimate this large would be 0.1% Since this is well below conventional thresholds (5% or 1%) we reject the null hypothesis → there is strong statistical evidence in the example of a negative association between class size and performance. - Control variables: Variables included to hold other factors constant and better isolate the effect of the variable of interest. Spiegazione easy:
È la variabile principale che stai studiando. Vuoi capire se e quanto questa variabile influenzi la tua variabile dipendente (Y).
Esempio: Vuoi studiare l'effetto dell'educazione (anni di studio) sul salario futuro di una persona.
Il mondo reale è complesso. Il salario di una persona non dipende solo dall'educazione, ma anche dall'esperienza lavorativa, dall'età, dal settore in cui lavora o dalle capacità innate.
Se inserisci nella regressione solo l'educazione, il coefficiente che stimi assorbirà anche l'effetto di tutte queste altre cose, creando una distorsione (chiamata in gergo Omitted Variable Bias o distorsione da variabile omessa).
Inserendo queste altre variabili come variabili di controllo (es. l'età o gli anni di esperienza), stai matematicamente dicendo a Stata: "Confronta individui che hanno lo stesso livello di esperienza e la stessa età, in modo da neutralizzare l'effetto di questi fattori".
Una volta che hai "bloccato" (tenuto costanti) l'esperienza e l'età, l'effetto che rimane e che viene stimato per la tua variabile di interesse (l'educazione) è "puro". È stato isolato dal rumore di fondo degli altri fattori.
Correlation is NOT causation When two variables are correlated, they move together but this does not imply causation. Often, a third factor is the real reason why both variables change. Some relationships are pure coincidence, not true cause-and-effect. To establish causation, we need an exogenous change in one variable and observe whether the other variable responds (for example, in an experiment) → Regression can show associations, but causality requires stronger assumptions Examples:
LECTURE 4
To clean messy data it is important to know several commands:
To create dummy variables
None
None
If your data has heteroskedasticity and you run a standard OLS regression without addressing it, two major things happen:
1. Visual Detection
After running your regression, you can plot the residuals against the fitted values to look for that classic fan shape:
Stata
regress prezzo metriquadri rvfplot, yline(0)
(If the points form an even band around the zero line, you are fine. If they fan out, you have heteroskedasticity).
2. Formal Tests You can run the Breusch-Pagan / Cook-Weisberg test right after your regression:
Stata
hettest
None
● A low p-value (p < 0.05) means you reject the null hypothesis of homoskedasticity, confirming that heteroskedasticity is present.
3. The Fix: Robust Standard Errors
The standard modern fix in econometrics is incredibly simple. You just tell Stata to compute Huber-White robust standard errors , which automatically correct the standard errors for any arbitrary form of heteroskedasticity:
Stata
regress prezzo metriquadri, robust
Using , robust doesn't change your β coefficients, but it adjusts the standard errors to make your p-values and hypothesis tests fully trustworthy again.
OTHER INTERESTING INFORMATION
Multicollinearity → It’s a phenomenon where two or more independent variables (X variables) in a multiple regression model are highly correlated with each other. In a perfect regression model, you want your independent variables to be correlated with the dependent variable (Y), but independent of each other. When they correlate heavily among themselves, it becomes difficult for Stata to isolate the individual effect of each variable. Why is Imperfect Multicollinearity a Problem?
Like heteroskedasticity, multicollinearity does not bias your β coefficients. Your estimates are still centered around the truth.
Instead, the problem is that it drastically inflates the variance and standard errors of your coefficients.
● High Standard Errors: Because OLS can't precisely tell which variable is doing the work, it becomes highly uncertain about its estimates. ● Low t-statistics and High p-values: Since t = β / SE, inflating the standard error drives your t-stat down. Consequently, variables that are actually very important might show up as statistically insignificant (p > 0.05). ● The Paradox: You might find yourself with a model that has a very high R^ (meaning your variables together explain price beautifully) and a significant overall F-test, yet none of your individual independent variables are statistically significant. ● Instability: Small changes in your data (like adding or removing a few rows) can cause your estimated coefficients to wildly jump or even swing from positive to negative.
TO TEST YOUR KNOWLEDGE GO TO: STATA DOMANDE