I've the data as follows and I need to calculate the percentage of difference between the variables 'amount1' and 'amount2' by ignoring the negative sign.
Input data:
AMOUNT1 | AMOUNT2 |
100 | 110 |
200 | 220 |
1000 | 100 |
100 | 20 |
1000 | 900 |
Desired Output:
AMOUNT1 | AMOUNT2 | Diff in percent |
100 | 110 | 10 |
200 | 220 | 10 |
1000 | 100 | 90 |
100 | 20 | 80 |
1000 | 900 | 10 |
Datastep to create the data:
data A;
Input AMOUNT1 AMOUNT2 ;
cards;
100 110
200 220
1000 100
100 20
1000 900
;
run;
If you want the differences shown with a percent sign, the easiest is to calculate the absolute relative difference, and use the PERCENT. format to display as a percent:
data want;
set a;
rel_diff=abs((amount1-amount2)/amount1);
format rel_diff percent5.0;
run;
You can use
data B;
set A;
diff=round(abs(AMOUNT2-AMOUNT1)/AMOUNT1*100);
run;
where abs is absolute value, i.e., ignoring negative. If you do not need round, then you can remove it.
What format should I use to display the percentage with percent sign (%) as shown below?
Diff in percent |
10% |
10% |
90% |
80% |
10% |
If you want the differences shown with a percent sign, the easiest is to calculate the absolute relative difference, and use the PERCENT. format to display as a percent:
data want;
set a;
rel_diff=abs((amount1-amount2)/amount1);
format rel_diff percent5.0;
run;
@Babloo wrote:
What format should I use to display the percentage with percent sign (%) as shown below?
Diff in percent 10% 10% 90% 80% 10%
Are you really too lazy to google "sas percent"?
@Babloo wrote:
Diff in percent 10%
Also, I don't think it's the best style to write both percent signs after the numbers and "in percent" in the header (same with other units of measurement).
Or try this:
data want;
set a;
if amount1>0 then diffpct=round(abs(amount2/amount1-1)*100,1e-9);
else diffpct=.;
label diffpct='Diff in percent';
run;
proc print data=want label noobs;
run;
Available on demand!
Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.
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.