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

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

# Re: st: Conditional Counter

 From Nick Cox To statalist@hsphsun2.harvard.edu Subject Re: st: Conditional Counter Date Mon, 15 Oct 2012 14:40:49 +0100

```At least one 7 is just

count if strpos(nnaadd, "7") > 0

count if strpos(string(nnaadd), "7") > 0

depending on whether -nnaadd- is string or numeric.

A related problem, how many 7s in each observation, is sweet:

If this is a string variable, the number of 7s is

gen sevens = length(nnadd) - length(subinstr(nnadd, "7", "", .))

Reasoning.

0. Measure the length of your string variable.

1. Imagine striking out every "7" in your variable.

2. Now work out how many characters shorter it would be.

If this is not a string variable, work on -string(nnadd)-.

gen sevens = length(string(nnadd)) - length(subinstr(string(nnadd),
"7", "", .))

See also

SJ-11-2 dm0056  . . . . . . . Stata tip 98: Counting substrings within strings
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  N. J. Cox
Q2/11   SJ 11(2):318--320                                (no commands)
tip on counting substrings within strings

On Mon, Oct 15, 2012 at 2:28 PM, Gonzalo DURAN SANHUEZA <giduran@puc.cl> wrote:
> Dear Statalist-Member, I have a variable it contains numbers:
>
> nnaadd
> 1234
> 3456
> 6543
> 7777
> 777
> 77
> 1267
> ...
>
> I need to ask stata to count the number of observations that have at
> least one 7..
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/faqs/resources/statalist-faq/
*   http://www.ats.ucla.edu/stat/stata/
```

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