[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

From |
David Kantor <dkantor@jhu.edu> |

To |
statalist@hsphsun2.harvard.edu |

Subject |
Re: st: Assigning prime numbers |

Date |
Thu, 12 May 2005 13:38:21 -0400 |

At 05:27 PM 5/12/2005 +0100, Steve (sdm1@york.ac.uk ) wrote:

I couldn't resist the temptation to try this -- to revisit a program that I did as a teenager, writing in Stata this time.Hi, I have a string variable which can take about 500 different values. I would like to assign a different prime number to each value of this string so that I get: String Prime A01 2 A02 3 A03 5 B01 7 C01 11 D02 13 F03 17 Etc Any suggestions would be most welcome! Thanks. Steve

Meanwhile, I noticed that someone has already submitted another solution. But here's mine anyway. This will create a variable called p to hold prime numbers.

gen long p = .

replace p = 2 in 1

forvalues n = 2 / `=_N' {

local primefound "0"

scalar j = p[`=`n'-1'] +1

local maxdiv = ceil(sqrt(scalar(j)))

while ~(`primefound') {

local divisible "0"

forvalues k = 1 / `=`n'-1' {

if p[`k'] > `maxdiv' {

continue, break

}

if mod(scalar(j), p[`k']) == 0 {

local divisible "1"

continue, break

}

}

if `divisible' {

scalar j = scalar(j) + 1

}

else {

replace p = scalar(j) in `n'

local primefound "1"

}

}

}

--------

Perhaps this can be made tighter, but it works.

This will place the first _N primes into your dataset. Now you didn't say whether the existing variable (which I presume is named String) is unique. If it is, then fine. If not, and you want to assign primes to each unique value of String, then you will need to play with the data first:

save the data in a tempfile

keep String (alone)

reduce to unique values of string

run the prime-generating code, as above

merge back to the saved tempfile.

I hope this is useful.

-- David

David Kantor

Institute for Policy Studies

Johns Hopkins University

dkantor@jhu.edu

410-516-5404

*

* For searches and help try:

* http://www.stata.com/support/faqs/res/findit.html

* http://www.stata.com/support/statalist/faq

* http://www.ats.ucla.edu/stat/stata/

**References**:**st: Assigning prime numbers***From:*sdm1@york.ac.uk

- Prev by Date:
**Re: st: Assigning prime numbers** - Next by Date:
**st: Survival Analysis** - Previous by thread:
**Re: st: Assigning prime numbers** - Next by thread:
**st: Survival Analysis** - Index(es):

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