Hello,
I am trying to implement a leave-one-out IV strategy in stata using an ado file which I leave below. My problem is that I don't know how to include a mata programe inside an ado file without having this error:
command end is unrecognized. I am saving the ado file in my personal adopath and then I call the program, below you have MWE:
MWE:
clear
input id location religiosity
1 1 4
2 1 6
3 1 8
4 2 5
5 2 10
end
leaveoutmean religiosity, by(location) gen(loo_religiosity)
list
And the program saved as leaveoneoutmean.ado in the personal adopath:
program define leaveoutmean
version 15
syntax varname, by(varname) gen(name)
local instrument `varlist'
local groupvar `by'
local outvar `gen'
foreach var in `instrument' `groupvar' {
capture confirm numeric variable `var'
if _rc {
di as error "Variable `var' must be numeric."
exit 198
}
}
gen double `outvar' = .
mata:
st_view(X = ., ., ("`groupvar'", "`instrument'"))
group = X[., 1]
inst = X[., 2]
N = rows(X)
loo = J(N, 1, .)
for (i = 1; i <= N; i++) {
this_group = group[i]
in_group = (group :== this_group)
in_group[i] = 0
ng = sum(in_group)
if (ng > 0) {
loo[i] = mean(select(inst, in_group))
}
}
st_store(., "`outvar'", loo)
end
end
Any help would be much appreciated.
Ruben
I am trying to implement a leave-one-out IV strategy in stata using an ado file which I leave below. My problem is that I don't know how to include a mata programe inside an ado file without having this error:
command end is unrecognized. I am saving the ado file in my personal adopath and then I call the program, below you have MWE:
MWE:
clear
input id location religiosity
1 1 4
2 1 6
3 1 8
4 2 5
5 2 10
end
leaveoutmean religiosity, by(location) gen(loo_religiosity)
list
And the program saved as leaveoneoutmean.ado in the personal adopath:
program define leaveoutmean
version 15
syntax varname, by(varname) gen(name)
local instrument `varlist'
local groupvar `by'
local outvar `gen'
foreach var in `instrument' `groupvar' {
capture confirm numeric variable `var'
if _rc {
di as error "Variable `var' must be numeric."
exit 198
}
}
gen double `outvar' = .
mata:
st_view(X = ., ., ("`groupvar'", "`instrument'"))
group = X[., 1]
inst = X[., 2]
N = rows(X)
loo = J(N, 1, .)
for (i = 1; i <= N; i++) {
this_group = group[i]
in_group = (group :== this_group)
in_group[i] = 0
ng = sum(in_group)
if (ng > 0) {
loo[i] = mean(select(inst, in_group))
}
}
st_store(., "`outvar'", loo)
end
end
Any help would be much appreciated.
Ruben
Comment