Announcement

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

  • How to generate a new variable based on conditions for values of two other variables

    Hello! I have the following dataset and I'm trying to create a new var X which should have the same empl value that its corresponding previous year and lower rank have -

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input int yearofdate byte(rank empl)
    2001 1  2
    2002 1  2
    2003 1  1
    2004 1  2
    2005 1  0
    2006 1  1
    2007 1  0
    2008 1  1
    2009 1  1
    2010 1  0
    2011 1  2
    2012 1  2
    2013 1  2
    2014 1  2
    2015 1  1
    2016 1  1
    2017 1  1
    2018 1  0
    2019 1  0
    2020 1  1
    2021 1  1
    2001 2  0
    2002 2  3
    2003 2  2
    2004 2  0
    2005 2  1
    2006 2  1
    2007 2  4
    2008 2  2
    2009 2  3
    2010 2  5
    2011 2  6
    2012 2  3
    2013 2  3
    2014 2  2
    2015 2  3
    2016 2  4
    2017 2  4
    2018 2  2
    2019 2  1
    2020 2  2
    2021 2  5
    2001 3  0
    2002 3  0
    2003 3  1
    2004 3  4
    2005 3  5
    2006 3  5
    2007 3  6
    2008 3  8
    2009 3  7
    2010 3  7
    2011 3  6
    2012 3  7
    2013 3  7
    2014 3  7
    2015 3  7
    2016 3  6
    2017 3  8
    2018 3 15
    2019 3 15
    2020 3 15
    2021 3 11
    2001 4  1
    2002 4  2
    2003 4  2
    2004 4  2
    2005 4  3
    2006 4  0
    2007 4  0
    2008 4  0
    2009 4  1
    2010 4  1
    2011 4  1
    2012 4  1
    2013 4  1
    2014 4  1
    2015 4  1
    2016 4  1
    2017 4  1
    2018 4  0
    2019 4  0
    2020 4  1
    2021 4  5
    2001 5  0
    2002 5  0
    2003 5  0
    2004 5  0
    2005 5  0
    2006 5  2
    2007 5  2
    2008 5  1
    2009 5  1
    2010 5  1
    2011 5  2
    2012 5  3
    2013 5  3
    2014 5  3
    2015 5  3
    2016 5  3
    end
    For example, if the year is 2002 and the rank is 1, the new variable X should have the empl value that exists for the year 2001 and rank 2 (i.e. 0). I thought the key was in sorting them appropriately, but I can't find the right way. Can someone help me with this please?

  • #2
    Code:
    tempfile temp
    save `temp'
    
    rename empl X
    replace yearofdate = year+1
    replace rank = rank-1
    merge 1:1 yearofdate rank using `temp', nogen keep(2 3)

    Comment


    • #3
      That worked perfectly, thank you so much! Appreciate it!

      Comment

      Working...
      X