data ds;
input x;
datalines;
1
2
3
4
5
-6
-7
-8
-9
;
run;
data t;
set ds;
if x>0 then do
y=x+x ;
if x<0 then do
y=x+x;
end;
end;
if x ge 0 then output;
if y le 0 then output;
run;
Here i am trying sum first five numbers and also do sum negivtive numbers in flag variable
data ds;
input x;
datalines;
1
2
3
4
5
-6
-7
-8
-9
;
run;
/*SQL*/
proc sql;
create table want as
select sum(x) as s
from ds
group by sign(x);
quit;
/*Datastep Hash method*/
data want;
if _n_=1 then do;
dcl hash H () ;
h.definekey ("_n_") ;
h.definedata ("sum") ;
h.definedone () ;
end;
set ds end=z;
if h.find(key:sign(x))=0 then sum=sum(sum,x);
else sum=x;
h.replace(key:sign(x),data:sum);
if z;
dcl hiter hi('h');
do while(hi.next()=0);
output;
end;
drop x;
run;
data want;
set ds end=z;
if _n_>1 and sign(x) ne lag(sign(x)) then do;
sum=0;
end;
sum+x;
run;
What does your desired result look like here?
HI Draycut
i want first 1 to 5 cumulative and also -6 to -9 values cumulative sum
Here is an alternative method:
data ds;
input x;
if x>0 then group=1;
else if x<0 then group=2;
datalines;
1
2
3
4
5
-6
-7
-8
-9
;
run;
proc means data=ds sum noprint;
var x;
by group;
output out=t (drop=_type_ _freq_) sum=grand_sum;
run;
please try
data ds;
input x;
if x gt 0 then grp=1;
else grp=2;
datalines;
1
2
3
4
5
-6
-7
-8
-9
;
run;
proc sql;
create table want as select sum(x) as sum, grp from ds group by grp;
quit;
data ds;
input x;
datalines;
1
2
3
4
5
-6
-7
-8
-9
;
run;
/*SQL*/
proc sql;
create table want as
select sum(x) as s
from ds
group by sign(x);
quit;
/*Datastep Hash method*/
data want;
if _n_=1 then do;
dcl hash H () ;
h.definekey ("_n_") ;
h.definedata ("sum") ;
h.definedone () ;
end;
set ds end=z;
if h.find(key:sign(x))=0 then sum=sum(sum,x);
else sum=x;
h.replace(key:sign(x),data:sum);
if z;
dcl hiter hi('h');
do while(hi.next()=0);
output;
end;
drop x;
run;
data want;
set ds end=z;
if _n_>1 and sign(x) ne lag(sign(x)) then do;
sum=0;
end;
sum+x;
run;
Somehow this looks like using a sledgehammer to swat a fly. This should be pretty close to the mark:
data want;
set have end=done;
if x > 0 then positive_total + x;
else negative_total + x;
if done;
run;
@Astounding wrote:
Somehow this looks like using a sledgehammer to swat a fly. This should be pretty close to the mark:
data want; set have end=done; if x > 0 then positive_total + x; else negative_total + x; if done; run;
This meets Saint-Exupery's definition of perfection.
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.
Ready to level-up your skills? Choose your own adventure.