DATA Step, Macro, Functions and more

Correct use of the "first." statement

Accepted Solution Solved
Reply
New Contributor
Posts: 2
Accepted Solution

Correct use of the "first." statement

Hi! I am working on a sas code including a loop to make a sum of food intakes. Every subject has an ID and for each ID I have different strings, one for each food item consumed during the day. The goal is to obtain the total amount eaten every day by each subject, i.e.: the sum of each food variable for every ID.

Here is the program I am using, which seems correct to me, but SAS keep saying that the variable first.id_no is not initialized:

data dataset; set dataset;

if first.id_no then do; sum0 = 0; sum1 = 0; sum2 = 0; sum3 = 0; end;

sum0 = sum0 + intake*(vegetables = 1);

sum1 = sum1 + intake*(fruit = 1);

sum2 = sum2 + intake*(cereals = 1);

sum3 = sum3 + intake*(fish = 1);

run;

Alternatively I have tried to write:

if (first.id_no) then do;

if first.id_no = 1 then do;

always getting the same error message from SAS.

Thanks for your help!


Accepted Solutions
Solution
‎02-05-2013 10:37 AM
Super Contributor
Posts: 358

Re: Correct use of the "first." statement

Posted in reply to Foodscience_76

In order to user the "first" and "last" you need to sort your data by the variable (in your case - id_no).

Proc sort data=dataset;

by id_no;

run;

data have;

set dataset

by id_no;

if first.id_no then   ...etc....

View solution in original post


All Replies
Super User
Posts: 5,441

Re: Correct use of the "first." statement

Posted in reply to Foodscience_76

I'm not sure about your code is doing what you want, but to make use of first. you must declare the column in a BY statement.

Data never sleeps
N/A
Posts: 1

Re: Correct use of the "first." statement

I often make this mistake. I have to go back and do a PROC SORT using the variable in the BY statement.

Solution
‎02-05-2013 10:37 AM
Super Contributor
Posts: 358

Re: Correct use of the "first." statement

Posted in reply to Foodscience_76

In order to user the "first" and "last" you need to sort your data by the variable (in your case - id_no).

Proc sort data=dataset;

by id_no;

run;

data have;

set dataset

by id_no;

if first.id_no then   ...etc....

Respected Advisor
Posts: 3,799

Re: Correct use of the "first." statement

Posted in reply to Foodscience_76

Foodscience_76 wrote:

The goal is to obtain the total amount eaten every day by each subject, i.e.: the sum of each food variable for every ID.

If this is your goal you will be better off using a procedure like MEANS/SUMMARY.

New Contributor
Posts: 2

Re: Correct use of the "first." statement

Posted in reply to Foodscience_76

Thank you everybody for your help! It was in fact very simple, just sorting and adding a BY statement.

🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
  • 5 replies
  • 244 views
  • 6 likes
  • 5 in conversation