Solved
New Contributor
Posts: 2

# first.variable help

[ Edited ]

I'm trying to output the first var3 for a first observation in a group of var1 AND var2, with output of var3 now var4.

Example data:

var1   var2  var3

1        1       100

1        1       200

2        1       300

2        1       400

2        2       500

Expected output:

var1  var2   var4

1        1       100

2        1       400

Here is my code, but it's not working as log shows first.var1 and first.var2 are uninititalized.

I'd appreciate any advice.

proc sort data=mydata out=mydata2; by var1 var2;

data mydata3;
set mydata2;
if FIRST.var1 and FIRST.var2 then
var4=var3;
run;

Accepted Solutions
Solution
‎05-07-2018 11:56 AM
Super User
Posts: 13,889

## Re: first.variable help

Posted in reply to samadams1965

First. and Last. processing require a BY statement. You were almost there:

data mydata3;
set mydata2;

by var1 var2;
if FIRST.var1 and FIRST.var2 then
var4=var3;
run;

But your shown example output of

2        1       400

does not match your description of wanting the First of var1 and first of var2 which would be

2        1       300

for your given example input

All Replies
Solution
‎05-07-2018 11:56 AM
Super User
Posts: 13,889

## Re: first.variable help

Posted in reply to samadams1965

First. and Last. processing require a BY statement. You were almost there:

data mydata3;
set mydata2;

by var1 var2;
if FIRST.var1 and FIRST.var2 then
var4=var3;
run;

But your shown example output of

2        1       400

does not match your description of wanting the First of var1 and first of var2 which would be

2        1       300

for your given example input

New Contributor
Posts: 2

## Re: first.variable help

Thanks for spotting my error and providing the missing BY as solution!

Trusted Advisor
Posts: 1,848

## Re: first.variable help

You asked for output of first observations by var1 and var2.

Did you mean first.var1 and first.var2 ?

I assumed no.

In this case the output should contain 3 obs:

```var1  var2   var4
1        1       100
2        1       400
2        2       500```

@ballardw's solution miss OUTPUT statement. As is you will get the all input obs in output.

So the solution should be:

``````data mydata3;
set mydata2;

by var1 var2;
if FIRST.var2 then do;
var4=var3;
output;
end;
drop var3;
run;``````

Alternative solution:

``````data mydata3(rename=(var3=var4));
set mydata2;
by var1 var2;
if FIRST.var2 then output;
run;``````

☑ This topic is solved.

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

Discussion stats
• 3 replies
• 130 views
• 2 likes
• 3 in conversation