[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

st: RE: Programming: Capturing bysort-parameters for use within a program

From   "Nick Cox" <>
To   <>
Subject   st: RE: Programming: Capturing bysort-parameters for use within a program
Date   Wed, 25 Mar 2009 17:03:30 -0000

In addition to good advice from Martin Weiss and Eva Poen: 

There is a reference in this program draft to a local macro `varlist-reference' which is never defined. You'd find also that that - is not acceptable as a character in a macro name. 

I would not write a program for the example problem, even with a need to apply this to multiple variables and a panel or similar structure. 

Given a -touse- flagging which observations to use, an identifier -id- and a time variable -timevar-. The basic recipe is 

foreach v of var <varlist> { 
	bysort touse id (timevar) : replace `v' = `v'[_n-1] if missing(`v') 

Any further -if- conditions can be combined as usual. So, rather than putting that in a program, I would just use that (kind of) code directly. 

On your more general point, I think you're confused on how to write byable programs. The main point is that -by:- takes care of most such details for you. Typically, you don't need to reproduce such control within a program. 

If further study of the documentation does not make this clear, perhaps you need to specify either another example problem (because this one doesn't call for a program) or another sample program that would actually work. 


Steinar Fossedal

I'm having trouble capturing the parameters for bysort used when
calling a program. The following simple (and untested) program
illustrates the problem. It replaces missing values with the
previously known value, using only a subset of the data.

capture program drop missing_like_last
program missing_like_last, byable(onecall)
      syntax varlist [if]
      marksample touse
      bysort `touse' `_byvars' (`varlist2-reference'): replace `var' =
`var'[_n-1] if `var'==. & `touse'

bysort id (sortvar): missing_like_last myvar if somevar==1

(syntax for bysort is: bysort varlist1 (varlist2): ...)

As you can see, I'm trying to issue commands using the exact same
bysort-parameters as used when calling the program, just adding the
`touse' variable. I need the order to be correct as I am issuing
commands with references between rows ( [_n-1] ).

To do this, I need to capture the -bysort- parameters varlist1 and
varlist2 containing the values id and sortvar. -_byvars- takes care of
varlist1, but how can I capture varlist2? Without specifying varlist2,
the sort order within id will be scrambled.

*   For searches and help try:

© Copyright 1996–2021 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index