Announcement

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

  • Error when running a macro

    When I ran the following macro

    cap prog drop VCC
    prog def VCC
    gen `1'=0
    replace `1'=1 if `2'
    tab `1'
    end

    VCC var "(v7107x==2 & (strpos(v7107,"B")>0 | strpos(v7107,"C")>0 | (v7107x==1 & v7107a==2)"


    I received the following error message:

    ----------------------------------------------------------------------------------------- begin VCC2 ---
    - gen `1'=0
    = gen var=0
    - replace `1'=1 if `2'
    = replace var=1 if (v7107x==2 & (strpos(v7107,
    too few ')' or ']'
    ------------------------------------------------------------------------------------------- end VCC2 ---
    r(132);



    Can someone please help me to figure out what is wrong in my syntax?


    Best,

    Nizam






  • #2
    It's just what the error message says: your parentheses are not balanced. Try
    Code:
    VCC var "(v7107x==2) & (strpos(v7107,"B")>0 | strpos(v7107,"C")>0 | (v7107x==1 & v7107a==2))"
    


    As an aside, the code you show
    Code:
    cap prog drop VCC
    prog def VCC
    gen `1'=0
    replace `1'=1 if `2'
    tab `1'
    end
    is not called a "macro" in Stata. Perhaps you have prior experience working with SAS, where they do use that terminology. In Stata this is called a program. It's important, when communicating with other Stata users, not to call it a macro because Stata does use the term macro to refer to something else. In fact, `1' and `2' are examples of what Stata calls macros.



    Comment


    • #3
      Originally posted by nizam khan View Post
      Can someone please help me to figure out what is wrong in my syntax?
      Apart from the unbalanced parentheses issue that Clyde mentions, you have quotes within quotes. You need compound double quotes in this instance. This is evident from your debugging output.

      ----------------------------------------------------------------------------------------- begin VCC2 ---
      - gen `1'=0
      = gen var=0
      - replace `1'=1 if `2'
      = replace var=1 if (v7107x==2 & (strpos(v7107,
      too few ')' or ']'
      ------------------------------------------------------------------------------------------- end VCC2 ---
      r(132);

      Code:
      VCC var `"(v7107x==2) & (strpos(v7107,"B")>0 | strpos(v7107,"C")>0 | (v7107x==1 & v7107a==2))"'
      Last edited by Andrew Musau; 29 Jun 2024, 23:24.

      Comment


      • #4
        On yet another level: I wouldn't write a program for this task at all.

        You want in this example to do something like

        Code:
        gen var = (v7107x==2 & (strpos(v7107,"B")>0 | strpos(v7107,"C")>0) | (v7107x==1 & v7107a==2)
        
        tab var
        and so a program to do that in one line saves one line out of two, as the cost of needing to include and explain that program somewhere else.

        Comment

        Working...
        X