Hello
In following raw data there are 3 fields: ID ,month, weight.
I want to check IF customer was exist in base month (1801) and give him value 1 if yes and 0 if no.
I want that value 1 or 0 will appear in all rows for the customer.
The task is to create a new column "InBaseMon" .
IF first raw of customer has month=1801 then InBaseMon=1.
IF first raw of customer has month=1801 then InBaseMon=0.
Then I want to retain the value of InBaseMon (from first row of customer to other rows of customer)
The expected values for new varaible "InBaseMon" for ID=1 are: 1 1 1
The expected values for new varaible "InBaseMon" for ID=2 are: 1 1 1
The expected values for new varaible "InBaseMon" for ID=3 are: 0 0
Data rawData;
Input ID month weight;
cards;
1 1801 100
1 1802 90
1 1803 85
2 1801 90
2 1802 94
2 1803 93
3 1802 78
3 1803 80
;
run;
Data tbl1;
set rawData;
by ID;
IF (first.ID AND month=1801) then InBaseMon=1;
Run;
I found solution
May anyone explain the code?
Data tbl1;
set rawData;
by ID;
retain InBaseMon ;
if first.ID then do;
InBaseMon=0;
if month eq 1801 then InBaseMon=1;
end;
Run;
/*Way2*/
Data tbl1;
set rawData;
by ID;
retain InBaseMon;
if first.ID and month eq 1801 then InBaseMon=1;
if first.ID and month ne 1801 then InBaseMon=0;
Run;
You require was
Then I want to retain the value of InBaseMon (from first row of customer to other rows of customer)
RETAIN will hold the value through observations until it is changed by the code.
@Ronein wrote:
I found solution
May anyone explain the code?
Data tbl1;
set rawData;
by ID;
retain InBaseMon ; * do not set InBaseMon to missing at the start of a data step iteration;
if first.ID then do; * do this in the first row for every id group;
InBaseMon=0;
if month eq 1801 then InBaseMon=1; * set inbasemon conditionally;
end;
Run;
The most compact method to set your variable is this:
data tbl1;
set rawdata;
by id;
retain inbasemon;
if first.id then inbasemon = ifn(month eq 1801,1,0);
run;
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.