SAS中YYMM格式日期计算月间隔失败:结果全为缺失值求助
Hey Roberto, let's break down why your code is returning missing values and walk through fixes and alternative methods to calculate that month difference.
First, Why Are You Getting Missing Values?
The most likely culprit here is a mismatch between the type of your original variables (numeric vs. character) and how you're using the input() function. Here's the breakdown:
- The
yymmn6.informat is designed to read character strings (like'200603') into SAS date values. - If your
fin_periodandperiodvariables are numeric (stored as numbers like200603instead of text), passing them directly toinput()will cause errors—SAS can't interpret the numeric value as a valid date string with that informat, resulting in missing values.
Fixing Your Original Code
Case 1: Your variables are character-type
If fin_period and period are stored as text (e.g., '200603'), your code is almost correct—double-check for typos in variable names or dataset references. You can confirm variable types with this quick check:
proc contents data=TIMES.INPUTS; run;
If they're character, your code should work once any typos are fixed.
Case 2: Your variables are numeric-type
You need to first convert the numeric value to a character string using put(), then use input() to turn it into a SAS date value:
data TIMES.TEST; set TIMES.INPUTS; /* Convert numeric YYMM to character, then to SAS date */ fin_date = input(put(fin_period, 6.), yymmn6.); period_date = input(put(period, 6.), yymmn6.); /* Calculate month difference */ difference = intck('month', fin_date, period_date); run;
The put(fin_period, 6.) ensures we get a 6-character string (e.g., '200603' from the number 200603) that the yymmn6. informat can correctly parse.
Alternative Method: Calculate Without SAS Date Values
If you want to avoid dealing with date formats entirely, you can directly compute the month difference by breaking down the YYMM value into year and month:
data TIMES.TEST; set TIMES.INPUTS; /* Split numeric YYMM into year and month */ fin_year = floor(fin_period / 100); fin_month = mod(fin_period, 100); period_year = floor(period / 100); period_month = mod(period, 100); /* Calculate total months difference */ difference = (period_year * 12 + period_month) - (fin_year * 12 + fin_month); run;
This method works for numeric YYMM values and skips the date conversion step entirely, which can be more straightforward for simple month difference calculations.
Quick Checks to Rule Out Other Issues
- Verify that
TIMES.INPUTSactually contains thefin_periodandperiodvariables (useproc contentsas mentioned). - Make sure there are no missing values in the original
fin_periodorperiodcolumns—if those are missing,differencewill also be missing.
内容的提问来源于stack exchange,提问作者Roberto

