Docsity

Appunti di COmputer Science - STATA, Appunti di Patente Europea del Computer (ECDL)

Toggle sidebar
bg1
02/03/2026
Elena Esposito
STATA
LECTURE 1
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
- Use "/Users/pupibiancone/Documents/UNI/Computer
Science/data/data_crimes.dta" → to open the dataset manually
whereas interactively you have to use file → import
- Describe → to have a description of the data before starting the analysis: it
tells us :Variable name, Storage type, Display format, Value label and
Variable label.
A string is a type of variable used to store text, such as names, words, or
codes.Unlike numeric variables, strings are not used for mathematical
calculations.
- Tabulate command: creates frequency tables, that is it summarizes how
many observations fall into each category of a variable (or combination of
variables)
- Browse (Br) → to have an entire image of the data that are shown in a
spreadsheet form.
- Summarize (Sum) → To have all the variables like mean, observations,
variance, it provides descriptive statistics for variables.
- Scatter Plot → it is a graph used to show the relationship between two
quantitative variables by plotting one on the x-axis and the other on the y-axis.
- Correlate (Corr) → It computes correlation coefficients between
variables [Pearson correlation coefficient]. It measures the strength and
direction of a linear relationship. The correlation ranges from –1 to +1, 0
means no linear relationship.
- Help [Command’s name]--> it tells the specific function that a command
does.
LECTURE 2
Introduction
To import (.xls) data there are two ways:
1) Interactively: File - Import - Excel Spreadsheet
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Anteprima parziale del testo

Scarica Appunti di COmputer Science - STATA e più Appunti in PDF di Patente Europea del Computer (ECDL) solo su Docsity!

02/03/ Elena Esposito

STATA

LECTURE 1

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

  • Use "/Users/pupibiancone/Documents/UNI/Computer Science/data/data_crimes.dta" → to open the dataset manually whereas interactively you have to use file → import
  • Describe → to have a description of the data before starting the analysis: it tells us :Variable name, Storage type, Display format, Value label and Variable label. A string is a type of variable used to store text, such as names, words, or codes.Unlike numeric variables, strings are not used for mathematical calculations.
  • Tabulate command: creates frequency tables, that is it summarizes how many observations fall into each category of a variable (or combination of variables)
  • Browse (Br) → to have an entire image of the data that are shown in a spreadsheet form.
  • Summarize (Sum) → To have all the variables like mean, observations, variance, it provides descriptive statistics for variables. - Scatter Plot → it is a graph used to show the relationship between two quantitative variables by plotting one on the x-axis and the other on the y-axis. - Correlate (Corr) → It computes correlation coefficients between variables [ Pearson correlation coefficient ]. It measures the strength and direction of a linear relationship. The correlation ranges from –1 to +1, 0 means no linear relationship. - Help [Command’s name]--> it tells the specific function that a command does.

LECTURE 2

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:

  • Variable names: Stata does not accept variable names starting with numbers (among other rules) Solution: Change it before in excel (one trick is to include just a letter before the numbers: e.g. 1998 to y1998)
  • Characters: Importing string data with latin characters - play with the encoding.
  • Missing values: Stata imported numeric data as strings because of some missing values. Solution: use the command destring maybe with option force
  • Size: Data is too big (because of storage type) - use compress, to store data efficiently

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:

  • Egen: it’s an extension of generate and allows us to create new variables using functions. I.e. egen furti_app_mean= mean(furti_app)--> this would create a variable equal to the mean of all observations.
  • Bysort: permette di ripetere lo stesso comando per diversi gruppi di osservazioni (ad esempio, calcolare la media separatamente per maschi e femmine, o per diversi anni). È un po' come dire a Stata: "Dividi i dati in gruppi e fai questa cosa per ogni gruppo".
  • Collapse:it converts the entire dataset into group-level statistics i.e. Example: collapse all crime data at the regional level collapse (mean) furti_app, by(cod_reg) This creates a new dataset with the average number of apartment burglaries by region → WARNING: The original dataset is lost Keeping the original data → To continue working with the original dataset, use in your do-file:
  1. preserve
  2. collapse (mean) furti_app, by(cod_reg)save regional_data.dta
  3. restore
  • Preserve and Restore: they’re used together to temporarily save and recover the dataset in memory
  • Append and Merge: When the datasets are related, we can combine them into a single dataset using these commands

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).

Un dettaglio fondamentale (Cosa succede dopo?)

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):

  1. nogen → merge 1:1 id using file.dta, nogen → Do not create the _merge variable.
  2. keep() →
  • merge 1:1 id using file.dta, keep(match)→ Keep only merged observations (_merge==3).
  1. Squaring leads to a unique and mathematically convenient solution: the function we minimize is ∑(y_i -(y_i ) ̂ )^2 has a parabolic u-shaped form. It means that there is only one minimum point → Therefore, there is a unique line that minimizes the sum of squared residuals → the OLS produces a single optimal solution.

Regression in Stata regress varlist [weight] [if exp][in range][,options]

  • The first variable in varlist is the dependent variable
  • The remaining variables are the independent variables
  • By using if , it is possible to restrict the estimation sample (you do not need to create a separate dataset)
  • The option in restricts the regression to a specific range of observations in the dataset.
  • The level() option specifies the width of the confidence interval, which tells us the range of plausible values for the true effect. The default is level(95)
  • An important option is robust, which computes robust standard errors. They measure how precise our coefficient estimates are. Robust standard errors make our statistical tests reliable when the variance (that measures how spread out a variable is around its mean) of the errors is not constant; so with robust standard errors we are being more conservative about statistical significance.

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:

1. La "Variable of interest" (Variabile di interesse)

È 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.

2. "Hold other factors constant" (Tenere costanti gli altri fattori)

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".

3. "Better isolate the effect" (Isolare meglio l'effetto)

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:

  • Ice cream and sunburn cases (positive correlation bc of the hot weather)
  • Umbrella and wet streets (positive correlation bc of the rain)
  • Shoe size and reading ability (positive correlation bc of the age)

LECTURE 4

To clean messy data it is important to know several commands:

  • replace [variablename]=subinstr([variablename],”€”,””,.)--> it replaces in all the values (since we put a point in the end) of the variable, the € with nothing
  • destring [variablename], replace dpcomma -> change the type of the variable, from a string to a number and the dpcomma explicitly tells Stata: "Look at the commas, treat them as the decimal separator, and convert them into standard American-style decimal points."

To create dummy variables

None

None

  • Residuals are not evenly spread
  • The dispersion increases with fitted values
  • A few large outliers, especially at high-predicted prices
  • This suggests heteroskedasticity. It justifies the use of robust standard errors

Why is Heteroskedasticity a Problem for OLS?

If your data has heteroskedasticity and you run a standard OLS regression without addressing it, two major things happen:

  1. OLS is still Unbiased: Your estimated coefficients (β) will still be centered around the true population parameters. The line isn't inherently tilted the wrong way because of it.
  2. Standard Errors are WRONG (The Real Danger): OLS will miscalculate the standard errors of your coefficients. Usually, it understates them. Because your standard errors are incorrect, your t-statistics , p-values , and confidence intervals are completely invalid. You might end up concluding that a variable is statistically significant when, in reality, it is not.
  3. OLS is no longer BLUE: It is no longer the Best Linear Unbiased Estimator because another method (like Weighted Least Squares) could yield estimates with smaller variance.

How to Detect and Fix It in Stata

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