Hi
How to assign jan 1 as start of week 1 of a year and a week should contain 7 days. i.e, Jan 1 to 7 is a week.
Pls advise.
Thanks
Does that mean the last week of the year can have less than 7 days? If so then below should work:
data have;
format dt date9.;
input dt:date9.;
week_in_year=ceil((dt-intnx('year',dt,0,'b')+1)/7);
datalines;
29dec2019
30dec2019
31dec2019
01jan2020
02jan2020
07jan2020
08jan2020
29dec2020
30dec2020
31dec2020
01jan2021
;
proc print;
run;
Please explain what you want as output. The week-function has a parameter to define the rules for numbering the first week of a year.
@andreas_lds wrote:
Please explain what you want as output. The week-function has a parameter to define the rules for numbering the first week of a year.
But those only determine if Sunday or Monday is the first day of a week, and if there's a week 0 or those days belong to the previous year.
You cam make it this into a function and forget about the logic.
Reusing @Patrick's formula:
proc fcmp outlib=WORK.FUNCS.DATE;
function week_from_1jan (DATE);
return( ceil((DATE-intnx('year',DATE,0,'b')+1)/7) );
endsub;
run;
options cmplib=WORK.FUNCS;
data _null_;
format DATE date9.;
input DATE date9.;
WEEK_IN_YEAR=week_from_1jan(DATE);
putlog DATE= WEEK_IN_YEAR= ;
datalines;
29dec2019
30dec2019
31dec2019
01jan2020
02jan2020
07jan2020
08jan2020
29dec2020
30dec2020
31dec2020
01jan2021
run;
Don't store the function in the WORK library though.
Use the julday. format:
data test;
input dt yymmdd10.;
format dt yymmddd10.;
week = ceil(input(put(dt,julday.),3.)/7);
datalines;
2019-12-31
2020-01-01
2020-01-02
2020-01-03
2020-01-04
2020-01-05
2020-01-06
2020-01-07
2020-01-08
2020-03-26
2020-12-31
;
Result:
dt week 2019-12-31 53 2020-01-01 1 2020-01-02 1 2020-01-03 1 2020-01-04 1 2020-01-05 1 2020-01-06 1 2020-01-07 1 2020-01-08 2 2020-03-26 13 2020-12-31 53
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.