Announcement

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

  • Perform additional condition after other conditions are met

    Dear Statalist,

    I am trying to generate a new variable NewCost based on another variable Cost. I want the generate the variable using data that meet three conditions (Time1<Time2, Type!=1, Time1 is the earliest). The last condition should be applied additionally among the data that are not exclude after the first two conditions. However, I don't want to drop any data because I still need the entire data table for next step of analysis.
    cost time1 time2 type newcost
    2.4 1997 1998 0 4.1
    5.6 2002 1998 0 4.1
    5.8 2001 1998 1 4.1
    4.1 1996 1998 0 4.1
    7.3 1996 1998 1 4.1
    I tried the following code but couldn't get what I wanted.
    Code:
    egen newcost = mean(cost) if (time1<time2&type!=1)&time1==time1[1]
    Any suggestion will be appreciated. Thanks!





  • #2
    The following code seems to do what you seek.
    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input float cost int(time1 time2) byte type float newcost
    2.4 1997 1998 0 4.1
    5.6 2002 1998 0 4.1
    5.8 2001 1998 1 4.1
    4.1 1996 1998 0 4.1
    7.3 1996 1998 1 4.1
    end
    
    generate seq = _n
    
    generate ignore = ! (time1<time2 & type!=1)
    sort ignore time1
    generate wanted = cost[1]
    
    sort seq
    drop seq
    Code:
    . list, clean
    
           cost   time1   time2   type   newcost   ignore   wanted  
      1.    2.4    1997    1998      0       4.1        0      4.1  
      2.    5.6    2002    1998      0       4.1        1      4.1  
      3.    5.8    2001    1998      1       4.1        1      4.1  
      4.    4.1    1996    1998      0       4.1        0      4.1  
      5.    7.3    1996    1998      1       4.1        1      4.1

    Comment

    Working...
    X