I have a dataset with dates and the corresponding months:
Date date9. Month yyyymm6.
2Jan2019 201901
28Feb2019 201902
31Jan2019 201901
31Dec2019 201912
1Jan2020 202001
31Mar2020 202003
I want to create a new variable as month_1 which takes the value of the next month if the date is the last day of the month. The resulting data would be like:
Date date9. Month yyyymm6. Month_1
2Jan2019 201901 201901
28Feb2019 201902 201903
31Jan2019 201901 201902
31Dec2019 201912 202001
1Jan2020 202001 202001
31Mar2020 202003 202004
How do I achieve this? Thank you!
data want;
set have;
month_1=date+1;
format month_1 YYMMN6.;
run;
or
data want;
set have;
length month_1 $6;
month_1=put(date+1,YYMMN6.);
run;
Try this
data have;
input Date :date9. Month :yymmn6.;
format Date date9. Month yymmn6.;
datalines;
02Jan2019 201901
28Feb2019 201902
31Jan2019 201901
31Dec2019 201912
01Jan2020 202001
31Mar2020 202003
;
data want;
set have;
if month(date) = month(date + 1) then Month1 = Month;
else Month1 = intnx('month', Month, 1, 'e');
format Month1 yymmn6.;
run;
Result:
Date Month Month1 02JAN2019 201901 201901 28FEB2019 201902 201903 31JAN2019 201901 201902 31DEC2019 201912 202001 01JAN2020 202001 202001 31MAR2020 202003 202004
length month_1 $6;
month_1 = put(intnx('month',date,1),yymmn6.);
Like this?
MONTH_1N=DATE+1;
MONTH_1C=put(DATE+1,yymmn6.);
@ChrisNZ when month=12 you will not get the right value:
201912 +1 = 201913 and not 202001
@Shmuel Variable DATE has format date9., so we have a sas date, and +1 always works.
data want;
set have;
month_1=date+1;
format month_1 YYMMN6.;
run;
or
data want;
set have;
length month_1 $6;
month_1=put(date+1,YYMMN6.);
run;
Assuming that "Month" and "Month_1" are alphanumeric:
data have;
input Date :date9. YearMonth $;
format Date date9.;
datalines;
2Jan2019 201901
28Feb2019 201902
31Jan2019 201901
31Dec2019 201912
1Jan2020 202001
31Mar2020 202003
;
data want;
set have;
Month_1 = put(date+1, yymmn6.);
run;
If a "Date" is the last day of a month adding one automatically shifts the date to first day of the next month.
EDIT: Hitting reload in the browser seems to be good idea, if a tab is open for more than an hour, preventing the duplication of answers.
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
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.