BookmarkSubscribeRSS Feed
AmirSari
Quartz | Level 8

Hi Everyone,

 

I am having trouble figuring out why first.id in the following code is not working. The problem is the value of var3 from id=1 is copied over to id=2. I am not sure why the first.id statement is ignored in this case. If you run the following code, you can see that the value of var3 id=1 is copied to var3 id=2 for the first two observations which are supposed to be zero.

Th code was provided by @Andreas_Ids

 

Any help is greatly appreciated!

data gwill;
input id gwill lag_gwill year;
cards;
1 100 . 2000
1 150 100 2001
1 130 150 2002
1 140 130 2003
1 150 140 2004
1 120 150 2005
1 110 120 2006
1 100 110 2007
1 140 100 2008
1 160 140 2009
1 180 160 2010
1 110 180 2011
2 200 . 2003
2 200 200 2004
2 170 200 2005
2 150 170 2006
2 150 150 2007
2 140 150 2008
2 170 140 2009

;
run;

data want;
set gwill;
by id;

retain start_year var1-var3;

if first.id then do;
start_year = year;
end;

select (year);
when (start_year) var1 = gwill / 10;
when (start_year + 1) var2 = (gwill - lag_gwill) / 10;
when (start_year + 2) var3 = (gwill - lag_gwill) / 10;
when (start_year + 10) var1 = 0;
when (start_year + 11) var2 = 0;
when (start_year + 12) var3 = 0;
otherwise;
end;

drop start_year;
run;

The results should look like this:

idgwillLag_gwillyearvar1var2 var3
1100 200010  
11501002001105 
11301502002105-2
11401302003105-2
11501402004105-2
11201502005105-2
11101202006105-2
11001102007105-2
11401002008105-2
11601402009105-2
1180160201005-2
1110180201100-2
2200 200320  
22002002004200 
21702002005200-3
21501702006200-3
21501502007200-3
21401502008200-3
21701402009200-3
4 REPLIES 4
Astounding
PROC Star

The value is held over because that's what you told SAS to do.  You said RETAIN those three variables, and that's what RETAIN means.

 

If you want to re-set var2 and var3 when you begin a new ID, you should say so.  In the statement(s) that are based on first.ID, re-set VAR2 and VAR3, not just VAR1.

AmirSari
Quartz | Level 8
Thanks for the clarification. How do I reset var1-var3 in order to get my desired output? Would you please provide the code? I am not an expert in SAS.
ballardw
Super User

@AmirSari wrote:
Thanks for the clarification. How do I reset var1-var3 in order to get my desired output? Would you please provide the code? I am not an expert in SAS.
   if first.id then do;
start_year = year;
call missing(var1, var2,var3);
end;

Will set var1, var2 and var3 to missing at the start of the ID group.

AmirSari
Quartz | Level 8
Thank you!
How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 1777 views
  • 3 likes
  • 3 in conversation