When I use if condition, it fails to mark sample even with marksample touse

29 Views Asked by At

I am coding ado files in Stata. I have a problem with marksample touse.

Here is an example of my code.

cap program drop mypro
program define mypro, sortpreseve byable(onecall)
version 16
syntax [anything] [if] [in] [, ///
cate(varlist) *]
marksample touse   
  if _by() {
            local BY `"by `_byvars'`_byrc0':"'
    }
 if "`cate'"!="" {
  local group `cate'
   bys `group': `BY' mycode `anything' `if' `in'
   }
  end

cap program drop mycode
program define mycode, sortpreseve byable(recall)
version 16
syntax [anything] [if] [in] [, *]
marksample touse 
  if _by() {
   quietly replace `touse'=0 if `_byindex' !=_byindex()
            
    }
tempvar dev values
gettoken 0:0
local yvar `1'
local xvar `2'

qui g `dev'=(`xvar'-0.5)^2
qui g `values'=(`dev'/`xvar' )^2+(`yvar'^2+`xvar'^2)/`dev'
qui su `values'
local final=`r(mean)'

di "values"
di `final'
end

My code includes two programs; mypro and mycode. The problem is when I use option cate. Usually the variable in the option cate is categorical.

When I run the code

mypro x1 y1, cate(group)

and the group variable contains

"A", "B", "C"

the code runs well.

The problem is when I use the program with if

mypro x1 y2 if year==2016, cate(group)

then the error message appears.

invalid syntax

The error message appears because the group variable contains only A and B values in 2016, but the code runs with group C.

I thought marksample would handle this if qualifier, but it fails. I've tried other things but I can't figure out how to solve this problem.

0

There are 0 best solutions below