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
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
  • 2 replies
  • 1100 views
  • 0 likes
  • 3 in conversation