BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
Foodscience_76
Calcite | Level 5

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!

1 ACCEPTED SOLUTION

Accepted Solutions
OS2Rules
Obsidian | Level 7

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

5 REPLIES 5
LinusH
Tourmaline | Level 20

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
happyuser
Calcite | Level 5

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

OS2Rules
Obsidian | Level 7

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....

data_null__
Jade | Level 19

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.

Foodscience_76
Calcite | Level 5

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

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

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
  • 5 replies
  • 1758 views
  • 6 likes
  • 5 in conversation