Saturday, June 6, 2009

Find out sum


There are two possible ways to find out the sum of variable x.

data dummy;
input pt $1 seq x;
datalines;
1 1 6
1 2 1
1 3 .
2 1 4
3 1 .
4 1 .
4 2 2
5 1 3
6 1 .
7 1 3
;
run;
proc sort data=dummy; by pt seq; run;

1. One can either transpose the value of variable x (by identifier seq) & find the sum.

proc transpose data=dummy out=dummy1 prefix=_;
by pt;
id seq;
var x;
run;

data sumt;
set dummy1;
val=sum(_1,_2,_3);
run;

2. Or can use the following code to calculate it.

The code given below calculates the sum of variable x without transposing data:

data sum;
set dummy;
by pt;
retain val;
if first.pt then do;
*set the value to missing when it reads first.pt;
val = .;
*& finds where x is non-missing to fill the column val with first.pt value;
if x ne . then val = x;
end;
*does an: addition of two value & retain the same;
else if x ne . & val ne . then val = val+x;
*incase when first.pt is missing & other records of the same pt are available: then fills the column val with value of x;
else if x ne . & val eq . then val = x;
run;

data sum1;
set sum;
by pt;
if last.pt;
keep pt x val;
run;

No comments:

Post a Comment