Announcement

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

  • Create a local adding numbers before every elements generated by tokenize

    Dear Stata users,

    I have three variables, I want to create a local that adds sequential number before each variable and interaction of the last two ones. Below is what I want to get:
    1 "mpg" 2 "rep78" 3 "foreign" 4 "rep78#foreign"

    Code:
    forvalues n= 1/4 { //In real applying case, the max number of `n' should be determined by count of variables plus 1.
        tokenize mpg rep78 foreign
        local first `1'
        local relabel `relabel' `n' "`first'"
    }
    
    display `"`relabel'"' //the result is certainly not what I desire: 1 "mpg" 2 "rep78" 3 "foreign" 4 "rep78#foreign"
    1 "mpg" 2 "mpg" 3 "mpg" 4 "mpg"

  • #2
    This may help.

    Code:
    local j = 0
    local example mpg rep78 foreign
    
    foreach v of local example {
        local ++j
        local `j' "`v'"
        local wanted `wanted' `j' "``j''"
        if `j' > 1 {
            local J = `j' - 1
            local pair ``J''#``j''
        }
    }
    
    mac li
    
    local ++j
    local wanted `wanted' `j' "`pair'"
    
    mac li
    EDIT This would need more code if it is expected to cope with just one variable name as input. Conversely. the test for j being above 1 isn't needed.
    Last edited by Nick Cox; 17 Feb 2025, 06:45.

    Comment


    • #3
      Dear Nick Cox, thank you as always. That's great!

      Comment

      Working...
      X