Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Trouble generating unique IDs: “too few variables specified”

    I wrote a Stata program to generate unique IDs with a specified length and number of observations. However, when I run it, I keep getting the error:

    Code:
    too few variables specified r(102)
    I’m not sure why Stata keeps throwing this error. Has anyone encountered this before or can suggest what might be going wrong?

    Any guidance would be much appreciated!

    Here is the code:
    Code:
    program define create_unique_ids
    
    // Syntax: create_unique_ids varname, n(#) length(#) seed(#)
    
    syntax varname, n(integer) length(integer) seed(integer)
    
    // Set seed for reproducibility
    
    set seed `seed'
    
    // Ensure there are observations
    
    if _N == 0 {
    
    di as error "No observations in memory. Create or import data first."
    
    exit 198
    
    }
    
    // Character pool: numbers + letters
    
    local chars "1234567890abcdefghijklmnopqrstuvwxyz"
    
    local k = strlen("`chars'") // number of characters in pool
    
    // Create variable if it does not exist, else clear it
    
    capture confirm variable `varname'
    
    if _rc {
    
    gen str`length' `varname' = ""
    
    }
    
    else {
    
    replace `varname' = ""
    
    }
    
    // Keep track of used IDs
    
    local used ""
    
    // Loop to generate n unique IDs
    
    forvalues i = 1/`n' {
    
    local id ""
    
    // Generate one ID of specified length
    
    forvalues j = 1/`length' {
    
    local I = ceil(runiform()*`k')
    
    local id = "`id'" + substr("`chars'", `I', 1)
    
    }
    
    // Ensure uniqueness
    
    while (strpos("`used'", "`id'") > 0) {
    
    local id ""
    
    forvalues j = 1/`length' {
    
    local I = ceil(runiform()*`k')
    
    local id = "`id'" + substr("`chars'", `I', 1)
    
    }
    
    }
    
    // Save ID to variable
    
    replace `varname' = "`id'" in `i'
    
    // Record as used
    
    local used = "`used' `id'"
    
    }
    
    end

  • #2
    See

    Code:
    help syntax
    Specifying

    Code:
    syntax varname
    is perfectly legal, but as documented in the help, the associated result of parsing input is returned in the local macro varlist.

    It's my guess that Stata threw you out as soon as you referred to local macro varname. It's not an error in itself to refer to a local macro that doesn't exist, but the consequence of doing that in this case is that a command doesn't see the variable name(s) it needs to do its job.

    Comment

    Working...
    X