Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: Assigning prime numbers

From   David Kantor <[email protected]>
To   [email protected]
Subject   Re: st: Assigning prime numbers
Date   Thu, 12 May 2005 13:38:21 -0400

At 05:27 PM 5/12/2005 +0100,  Steve ([email protected] ) wrote:

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

Any suggestions would be most welcome!


I couldn't resist the temptation to try this -- to revisit a program that I did as a teenager, writing in Stata this time.

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
[email protected]

* For searches and help try:

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