Quartz | Level 8

## Retain with multiple first statements

This is the data I have and want.

``````data want;
input ID visit question response v1_response;
cards;
1 1 1 4 4
1 2 1 3 4
1 1 2 6 6
1 2 2 9 6
;``````

Basically, I want to create variable v1_response, where it shows the visit 1 response by ID and question in order to calculate the change from visit 1 score for each question. I know how to do this when it is only 1 question in the dataset. But my approach is keeping only the value of the first question across all questions.

This is my code so far

``````data have;
input ID visit question response;
cards;
1	1	1	4
1	2	1	3
1	1	2	6
1	2	2	9
;

proc sort data=have;
by ID visit question;
run;

data want;
set have;
by ID visit question;

retain v1_response;

if first.ID  AND first.question and visit=1 then do;
v1_response=response;
end;
else if visit GT 1 do;
change=response-v1_response;
end;

run;``````

1 ACCEPTED SOLUTION

Accepted Solutions
Tourmaline | Level 20

## Re: Retain with multiple first statements

``````data want;
input ID visit question response v1_response;
cards;
1 1 1 4 4
1 2 1 3 4
1 1 2 6 6
1 2 2 9 6
;

data want2;
set want;
by id question;
retain want;
if first.question then want=response;
run;``````
4 REPLIES 4
Tourmaline | Level 20

## Re: Retain with multiple first statements

``````data want;
input ID visit question response v1_response;
cards;
1 1 1 4 4
1 2 1 3 4
1 1 2 6 6
1 2 2 9 6
;

data want2;
set want;
by id question;
retain want;
if first.question then want=response;
run;``````
Quartz | Level 8

## Re: Retain with multiple first statements

THanks, this did work for me. So basically, i don't sort it by visit also it looks like.

However, how does SAS know, which is the first visit?

Super User

## Re: Retain with multiple first statements

Because of the by statement, SAS keeps track of the by variables, and sets the first. and last. variables at every group change.

Super User

## Re: Retain with multiple first statements

Keep the order as is, run the data step with

``by id question;``

and set v1_response at first.question.

Discussion stats
• 4 replies
• 436 views
• 0 likes
• 3 in conversation