Announcement

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

  • Repeat the value after the first appearance

    Hello! I hope you can help me with the next task

    Here is an extract of my data set

    The variable trans adopts the value of 0 or 1. After the first appearance of “1” in the variable trans for a product code for a country, the value of trans should be 1 for the rest of the years for that product code for that country. For example, if the first time the trans value is 1 for product code 721070 of country 410 is in 1997, then from 1998 to 2021, the value of trans should be replaced by 1. My data set goes from 1995 to 2021, I have 20 countries and thousands of different product codes.

    Year Country ProductCode trans
    1996 410 721050 1
    1996 410 721060 0
    1996 410 721070 0
    1997 410 721050 1
    1997 410 721060 1
    1997 410 721070 1
    1998 410 721050 0
    1998 410 721060 0
    1998 410 721070 0
    1996 230 721050 0
    1996 230 721060 0
    1996 230 721070 0
    1997 230 721050 1
    1997 230 721060 1
    1997 230 721070 1
    1998 230 721050 0
    1998 230 721060 0
    1998 230 721070 0
    Thank you in advance [COLOR=inherit !important]


    [/COLOR]

  • #2
    Please use dataex as here and as requested in FAQ Advice #12.

    I wouldn't overwrite an existing variable unless you are completely sure you'll never want it again and that your replacement code is exactly right. Even then someone else may want to see the original data.

    This may help otherwise.


    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input int(year country) long productcode byte trans
    1996 410 721050 1
    1996 410 721060 0
    1996 410 721070 0
    1997 410 721050 1
    1997 410 721060 1
    1997 410 721070 1
    1998 410 721050 0
    1998 410 721060 0
    1998 410 721070 0
    1996 230 721050 0
    1996 230 721060 0
    1996 230 721070 0
    1997 230 721050 1
    1997 230 721060 1
    1997 230 721070 1
    1998 230 721050 0
    1998 230 721060 0
    1998 230 721070 0
    end
    
    gen wanted = trans 
    bysort country productcode (year) : replace wanted = 1 if wanted[_n-1] == 1

    Comment


    • #3
      Many many thanks Nick! It is working

      Comment

      Working...
      X