I wanted to calculate the Indian financial quarter which starts in April (April-Jun would be 1st Qtr). I created a user defined function using the proc fcmp procedure yet it is not giving me the correct answer. What is wrong with my logic?
proc fcmp outlib=three.level.name;
function FinQuart(dat);
if month(dat) in(4,5,6) then qurt = 1;
if month(dat) in(7,8,9) then qurt = 2;
if month(dat) in(10,11,12) then qurt = 3;
if month(dat) in(1,2,3) then qurt = 4;
return (qurt);
endsub;
run;
The function returns 4 whatever value you submit.
Well, that example is incorrect. You are taking the month number from 12DEC09, and putting that into the variable TT. Then you call you function with this variable, hence you are calling as:
tempvar=finquart(12);
Then in your function, you are using the month() function which expects a date (which is a number of days since a certain date), and are passing it 12, which SAS takes as a date number (formatted would be 13JAN1960), and Jan which is month 1 comes out as QTR=4. So correct to this:
options cmplib=twolevel.name; data temp; tt = month('12DEC09'd); put tt; actual_date_variable='12DEC09'd; tempvar = FinQuart(actual_date_value); run;
Please post test data in the form of a datastep. Personally I would write a datastep to do this, you can then easily debug it and save it for later or put it in a macro if needed. Compiled functions whilst a nice gimmick, are hard to use, proprietary, and obfuscated.
I was testing the function in a datastep itself.
options cmplib=twolevel.name;
data temp;
tt = month('12DEC09'd);
put tt;
tempvar = FinQuart(tt);
run;
output
tt tempvar
12 4
Well, that example is incorrect. You are taking the month number from 12DEC09, and putting that into the variable TT. Then you call you function with this variable, hence you are calling as:
tempvar=finquart(12);
Then in your function, you are using the month() function which expects a date (which is a number of days since a certain date), and are passing it 12, which SAS takes as a date number (formatted would be 13JAN1960), and Jan which is month 1 comes out as QTR=4. So correct to this:
options cmplib=twolevel.name; data temp; tt = month('12DEC09'd); put tt; actual_date_variable='12DEC09'd; tempvar = FinQuart(actual_date_value); run;
A custom function is good, but you can also use a nested function.
Quarter = qtr(intnx('month', date, -3, 'b'));
Have you set the cmplib value?
Options cmplib=...?
I can't believe I made such a silly mistake. Thanks a lot. Yes, I have specified the cmplib option. I am new to SAS so I had no idea about nested functions. Thanks again.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.