Announcement

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

  • Adding scalar to all values of local macro

    How to we get a local macro with unique values of a given variable + 1?

    The code below outputs a local macro with the unique values of var1. How do I then get another macro with each one of those values + 1?

    Code:
    clear
    input float var1
    1
    10
    5
    5
    7
    end
    
    levelsof var1, local(v1)
    display "`v1'"
    I tried the following but it does not work.
    Code:
    local v1_plus1 = `v1' +1

  • #2
    Two solutions.
    Code:
    . input float var1
    
              var1
      1. 1
      2. 10
      3. 5
      4. 5
      5. 7
      6. end
    
    .
    . levelsof var1, local(v1)
    1 5 7 10
    
    . display "`v1'"
    1 5 7 10
    
    .
    . // easy solution
    . generate var2 = var1+1
    
    . levelsof var2, local(v2)
    2 6 8 11
    
    . drop var2
    
    . display "`v2'"
    2 6 8 11
    
    .
    . // loopy solution
    . local v3
    
    . foreach v of local v1 {
      2.     local v3 `v3' `=`v'+1'
      3. }
    
    . display "`v3'"
    2 6 8 11
    
    .
    Added in edit: the solution
    Code:
    local v1_plus1 = `v1' +1
    does not work because after substituting for `v1' the command becomes
    Code:
    local v1_plus1 = 1 5 7 10 +1
    and the expression to the right of the equal sign is not a syntactically correct Stata expression.
    Last edited by William Lisowski; 10 Jan 2022, 15:22.

    Comment


    • #3
      I have no idea why you want this and whether your real examples are comparable in size, but I did this with your data example:


      Code:
      . mata 
      ------------------------------------------------- mata (type end to exit) ------------------------------
      : values = uniqrows(sort(st_data(., "var1"), 1))' 
      
      : values 
              1    2    3    4
          +---------------------+
        1 |   1    5    7   10  |
          +---------------------+
      
      : values :+ 1 
              1    2    3    4
          +---------------------+
        1 |   2    6    8   11  |
          +---------------------+
      
      : end

      Comment

      Working...
      X