Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at

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

Re: st: Loop-within-loop error while looping over observations for a microsimulation

From   Nick Cox <>
Subject   Re: st: Loop-within-loop error while looping over observations for a microsimulation
Date   Mon, 6 Aug 2012 16:56:23 +0100

Daniel has explained the message about weights.

The restriction on -forvalues- should be clear in either of two ways.

1. If you look at the examples for -foreach- and -forvalues- you will
see that they always cycle over specified ranges.

Something like

local foo = 42
forval j = 1/`foo' {
      di "`j'"

is not an exception because the macro reference to `foo' is evaluated
before -forvalues- gets to work.

2. If you supply a Stata variable as either limit to a -forvalues- the
question for you is how do you expect Stata to know which value of
that variable to use? In essence, it can't know what you intend.


On Mon, Aug 6, 2012 at 3:50 PM, Stephen Cranney
<> wrote:
> monthsofpostpartum was a variable for how many months of infertility
> are expected because of a birth.Therefore, the forvalues j=
> 0/monthsofpostpartum is attempting to capture the month/year sequences
> that come after childbirth up to monthsofpostpartum
> I wasn't aware that forvalues had that restriction. I'll change that
> to an inputted macro elsewhere. However, when I change the
> monthsofpostpartum variable to a constant (in this case 12), it's
> giving me a "weights not allowed" sign.
> On Mon, Aug 6, 2012 at 8:35 AM, Nick Cox <> wrote:
>> What is -monthsofpostpartum-? -foreach- and -forvalues- won't evaluate
>> for you what is not evaluated otherwise. Here -monthsofpostpartum-
>> needs to be replaced by some constant.
>> Nick
>> On Mon, Aug 6, 2012 at 3:29 PM, Stephen Cranney
>> <> wrote:
>>> I'm trying to write a program that involves population microsimulation.
>>> Each individual has a column for year and month, and the data is sorted
>>> accordingly. I'm trying to loop through the observations with a stochastic
>>> binomial function to simulate a birth occurring, but am then trying to
>>> simulate the months of postpartum infertility so that it doesn't have the
>>> individual getting pregnant twice in two months. Postpartum infertility is
>>> indicated by .i and all of the fertile-time data is automatically indicated
>>> by .f My syntax is below, but I keep getting an invalid syntax error and
>>> can't figure out what I'm doing wrong.
>>> Thanks in advance,
>>> local N = _N
>>> forvalues i = 1/`N' {
>>>     forvalues j= 0/monthsofpostpartum {
>>>         replace childbirth= rbinomial(1, probabilityconceive) if childbirth== .f
>>>         replace childbirth[_n+j]== .i if childbirth [`i'] == 1
>>>         }
>>>     }
*   For searches and help try:

© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index