Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down on April 23, and its replacement, is already up and running.

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

Re: st: More elegant code . . .?

From   Stas Kolenikov <>
Subject   Re: st: More elegant code . . .?
Date   Sat, 4 Jun 2011 23:20:41 -0500

On Sat, Jun 4, 2011 at 6:18 PM, Michael Costello
<> wrote:
> Statalisters,
> I have some code that I would like to make more elegant (shorter,
> while still fitting on one line):
> recode letter_auto_stop 0=1 if letter1==0 & letter2==0 & letter3==0 &
> letter4==0 & letter5==0 & letter6==0 & letter7==0 & letter8==0 &
> letter9==0 & letter10==0
> The line above works, but it's bulky.  I'd like to find something
> better to use.  I tried:
> recode letter_auto_stop 0=1 if letter1-letter10==0
> but stata treated it as "recode letter_auto_stop 0=1 if letter1==0 &
> letter10==0" ignoring letter2 through letter9 entirely.

No. Stata treated it exactly the way you asked: letter1 - letter10 ==
0, meaning letter1==letter10, of course. This is not a varlist, this
is a subtraction.

Here's an option you could consider:

egen byte torecode = anycount( letter1-letter10 ), values(0)
recode  letter_auto_stop 0=1 if torecode

Generally, you should not trust the variable ranges, though, as that
is a way to disaster when for some reason the order of the variables
in the data set may change. However, treating this hidden problem
properly would require a cycle, and with a cycle, you could do things
entirely differently, anyway.

local iflist 1
gen byte torecode = 1
forvalues k=1/10 {
   local iflist `iflist' & letter`k' == 0
   replace torecode = torecode & ( letter`k' == 0 )
* either
recode [whatever] if torecode
* or
recode [whatever] if `iflist'

I am not sure either construct qualifies as less bulky, but I would
view either version as more reliable and less error-prone to copying
and pasting.

Stas Kolenikov, also found at
Small print: I use this email account for mailing lists only.

*   For searches and help try:

© Copyright 1996–2016 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index