Skip to Main Content

Reading data from Stata into Mata | Stata Code Fragments

/* input data into Stata */
input y x0 x1 x2
7 1 2 1
15 1 4 4
20 1 3 7
15 1 6 3
12 1 5 2
8 1 1 2
end

save test.dta

mata
/* read data into Mata */
X = st_data(.,("x0","x1","x2"))
X
y = st_data(.,"y")

/* find b */
b = qrinv(X'*X)*(X'y)

/* make predictions */
yp = X * b
ye = y - yp

stata(`"display "Predictor Variables""')
X
stata(`"display "Predicted Variable""')
y
stata(`"display "Parameter Estimates""')
b
stata(`"display "Predicted Value of Y""')
yp
stata(`"display "Error in Prediction of Y""')
ye

/* create a vector to tell Stata which observations to put b into */
nb = (123)

/* Write out b into the dataset */
(void) st_addvar("float","b")
st_store(nb,"b",b)
end

label var b "parameter"
save test, replace