Numeric and Date Functions
Prerequisites: Formats, informats, and dates
Numeric functions
data _null_;
r = round(3.14159, 0.01);
c = ceil(2.1);
f = floor(-2.1);
i = int(-2.7);
m = mod(17, 5);
big = max(3, 9, 4);
avg = mean(2, 4, 9);
cnt = n(1, ., 3);
miss = nmiss(1, ., 3);
put r= c= f= i= m= / big= avg= cnt= miss=;
run;
r=3.14 c=3 f=-3 i=-2 m=2
big=9 avg=5 cnt=2 miss=1
ROUND(x, unit)rounds to the nearest multiple ofunit—round(x, 5)rounds to the nearest 5.INTdrops the decimals (toward zero);FLOORrounds down.- Statistical functions (
SUM,MEAN,MIN,MAX,STD,N,NMISS) work across variables in one row and skip missing values. Useoffor lists:sum(of sales1-sales12).
Date intervals
INTCK counts interval boundaries between two dates; INTNX moves a date
by a number of intervals:
data _null_;
start = '15JAN2024'd;
stop = '10MAR2024'd;
months = intck('month', start, stop);
full_months = intck('month', start, stop, 'c');
next_begin = intnx('month', start, 1);
next_end = intnx('month', start, 1, 'end');
next_same = intnx('month', start, 1, 'same');
put months= full_months=;
put next_begin= date9. next_end= date9. next_same= date9.;
run;
months=2 full_months=1
next_begin=01FEB2024 next_end=29FEB2024 next_same=15FEB2024
- By default
INTCKcounts boundaries crossed: 15 January to 10 March crosses 1 February and 1 March, so2. The'c'(continuous) method counts complete months instead: only one full month has passed. INTNXaligns to the beginning of the interval by default;'end'and'same'change that. 2024 is a leap year, hence 29 February.- Other intervals:
'day','week','qtr','year', and more.
Ages
data _null_;
age = yrdif('20JUN2000'd, '15MAR2024'd, 'age');
whole = floor(age);
put whole=;
run;
whole=23
YRDIF with the 'age' basis gives a fractional age; floor makes it
whole years — the person turns 24 in June 2024.
Times and datetimes
- A time is seconds since midnight:
'09:30'tis 34200. - A datetime is seconds since midnight, 1 January 1960:
'15MAR2024:09:30:00'dt. DATEPART(dt)andTIMEPART(dt)split a datetime;DHMS(date, h, m, s)builds one. Formats:time8.,datetime20..
Converting between SAS datetimes and Unix timestamps is a common chore — they differ by the 10 years between 1960 and 1970. The Unix Epoch Converter helps you check your arithmetic.
Practice
For the date 15 March 2024, find the last day of its quarter and how many days remain until then.
Show solution
data _null_;
d = '15MAR2024'd;
qend = intnx('qtr', d, 0, 'end');
left = qend - d;
put qend= date9. left=;
run;
qend=31MAR2024 left=16