Announcement

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

  • Two loops

    Dear All,

    I have the following column containing year of observations:

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input int year
    2016
    2011
    2016
    2012
    2011
    2002
    2002
    2001
    2001
    2016
    2011
    2008
    2007
    2005
    2003
    2003
    2002
    2013
    2012
    2011
    2011
    2004
    2013
    2012
    2005
    2002
    2000
    2013
    2010
    2005
    2003
    2005
    2007
    2004
    2006
    2006
    2003
    2009
    2004
    2009
    2007
    2006
    2010
    2008
    2004
    2000
    2002
    2008
    2001
    2010
    2010
    2006
    2009
    2006
    2005
    2008
    2009
    2008
    2007
    2004
    2010
    2016
    2016
    2015
    2015
    2015
    2015
    2015
    2014
    2014
    2014
    2014
    2014
    2013
    2013
    2012
    2012
    2009
    2007
    2003
    2001
    2001
    2000
    2000
    2000
    end
    Years go from 2000 to 2016. I would like to create a new variable "trend", which takes the value of 1 if year=2000; 2 if year=2001 and so on.

    I tried a double loop:

    Code:
    gen trend=0
    forval i=2000/2016{
    forval n=1/17{
    replace trend=`n' if year==`i'
    }
    }
    However I do not get what I expected. I am making some mess with the two loops I guess. Any hint?

    Thanks in advance
    Last edited by Dario Maimone Ansaldo Patti; 20 Nov 2018, 09:08.

  • #2
    Hi Dario,
    you don't need any loop here.

    Code:
    bys year: gen v = _n
    bys v (year): gen v2 = _n
    bys year (v): gen trend = v2[1]
    drop v v2
    tab year trend

    Best,
    Raffaele

    Comment


    • #3
      No loops needed.

      Code:
      gen trend = year - 1999
      I didn't look carefully at your loops. They feature a variable S020 which isn't in your data example.

      Comment


      • #4
        Dear Nick,

        you are always helpful. It seems I like to complicate my life! I amended the text in my question. Actually S020=year.

        Thanks again.

        Comment


        • #5
          Hi Raffaele. Nick provided an easier approach. But thanks for your suggestion.

          Comment

          Working...
          X