Announcement

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

  • How to shorten multiple line of codes relevant?

    In my data, I have a numeric number called year which have value from 2 to 22, I want to replace this variable by a variable year1 which have the value from 2001 to 2021.
    For sure the very clear way to do is:

    Code:
    gen year1=.
    replace year1=2001 if (year==2)
    replace year1=2002 if (year==3)
    .replace year1=2003 if (year==4)
    .
    .
    .
    (similar code)
    However, it is around 21 lines of code and it is not necessarily like that from my point of view. I have a look at some ways to shorten it. For example, by using the semicolon delimiter as mentioned in this archive.
    My code is

    Code:
    replace year1=2001 if (year==2); replace year1=2002 if (year==3)
    However, it turns out the error like that
    Code:
    unknown function ()
    r(133);
    Could you please help me to sort it out?Thanks in advance




  • #2
    It's just one line:
    Code:
    gen year1 == 1999+year

    Comment


    • #3
      The specific code you have is replaced perfectly by the line provided in #2. If you had other code where you wanted to use the semi-colon, you would need to get Stata to change the delimiter, a bit like this:
      Code:
      #delimit ;
      
      command 1 ; command 2 ; command 3;
      
      very long
      command
      spread over
      many lines ;
      
      #delimit cr
      The main use of this feature is actually not to shorten the command; it is largely used when you want to split up a very long command that is hard to read on one line (and/or you find it painful to split it up using three forward slashes /// ).
      Last edited by Hemanshu Kumar; 12 Sep 2022, 23:05.

      Comment


      • #4
        Originally posted by Clyde Schechter View Post
        It's just one line:
        Code:
        gen year1 == 1999+year
        Thanks Clyde Schechter , However, when I typed the command suggested
        Code:
        gen year1 == 1999+year
        It showed that
        Code:
        == invalid name
        r(198);
        Could you please kindly to help me in sorting it out?

        Comment


        • #5
          I sorted it already, we have one redundant "=". The code should be:

          g
          Code:
          en year1=1999+year

          Comment


          • #6
            Yes, sorry for that typo.

            Comment

            Working...
            X