DATA Step, Macro, Functions and more

Please help!!!!

Reply
N/A
Posts: 1

Please help!!!!

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
Valued Guide
Posts: 634

Re: Please help!!!!

Posted in reply to Hellomeitis
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]
Super User
Posts: 10,044

Re: Please help!!!!

Posted in reply to Hellomeitis
[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
Ask a Question
Discussion stats
  • 2 replies
  • 111 views
  • 0 likes
  • 3 in conversation