BookmarkSubscribeRSS Feed
Hellomeitis
Calcite | Level 5
Hello all,

I'm new to this forum. the data is like this:

data a;
A='101';order=1;val=25;p=0;output;
A='101';order=2;val=54;p=0;output;
A='101';order=3;val=66;p=1;output;
A='101';order=4;val=85;p=1;output;
A='101';order=5;val=99;p=0;output;
A='101';order=6;val=120;p=0;output;
A='101';order=7;val=135;p=1;output;
A='101';order=8;val=170;p=1;output;
A='101';order=9;val=186;p=1;output;
A='101';order=10;val=190;p=1;output;
A='101';order=11;val=195;p=1;output;
run;

I've to calculate the difference of two consecutive p=1 i.e., output should have 2 obs with difference of first p=1 and last p=1. Please help.
Name Diff
A 85-66
A 195-135
2 REPLIES 2
ArtC
Rhodochrosite | Level 12
Assuming I understand the question, consider the following DATA step:

[pre]
Data diff;
set a;
if p=0 then cnt=0;
cnt+p;
lastv=lag(val);
if cnt ge 2 then diff = val - lastv;
output;
run;
[/pre]
Ksharp
Super User
[pre]
data a;
A='101';order=1;val=25;p=0;output;
A='101';order=2;val=54;p=0;output;
A='101';order=3;val=66;p=1;output;
A='101';order=4;val=85;p=1;output;
A='101';order=5;val=99;p=0;output;
A='101';order=6;val=120;p=0;output;
A='101';order=7;val=135;p=1;output;
A='101';order=8;val=170;p=1;output;
A='101';order=9;val=186;p=1;output;
A='101';order=10;val=190;p=1;output;
A='101';order=11;val=195;p=1;output;
run;
data temp;
set a;
retain flag 0;
if p ne lag(p) then flag+1;
run;
data result;
set temp;
by flag;
retain pre;
if first.flag then pre=val;
if last.flag and p then do;
Name='A';
Diff=catx('-',val,pre);
output;
end;
keep Name Diff;
run;
proc print;
run;

[/pre]


Ksharp

SAS Innovate 2025: Call for Content

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!

Submit your idea!

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 2 replies
  • 802 views
  • 0 likes
  • 3 in conversation