BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
KyuL
Calcite | Level 5

Hi,

Attached is the "president.txt" file.

The question asked me to use substr() function to create a new character variables to hold the day, month, and year from variable DOBC. 

I tried the function but it didn't work.

Could anyone help me to correct the code? Thanks a lot. 

filename TXTfile '/folders/myfolders/Assignment 2/President.txt';
data President;
 infile TXTfile expandtabs lrecl=300 truncover;
 input @1 FullName $22. 
       @25 City $19. 
       @49 State & $20. 
       ASP :2. 
       DOB :mmddyy10. 
       Term :4. 
       Votes :comma10. 
       PercVote :percent10.2 
       ;
 DOBC = DOB;
 DOBC2 = DOB;
 format DOB mmddyy10. Votes comma10. PercVote percent10.2 
        DOBC date9. DOBC2 ddmmyy10.;
run;

data test;
 set President;
 length day $2 mon $3 year $4;
 
 day = substr(DOBC,1,2);
 mon = substr(DOBC,3,3);
 year = substr(DOBC,6);
run;
1 ACCEPTED SOLUTION

Accepted Solutions
Kurt_Bremser
Super User

SUBSTR is a character function, dates are numbers (count of days from 1960-01-01) and stored in numeric variables.

The question makes therefore no sense in a SAS context.

For dates, you use the DAY, MONTH and YEAR functions to extract those numeric values from a date.

View solution in original post

4 REPLIES 4
Kurt_Bremser
Super User

SUBSTR is a character function, dates are numbers (count of days from 1960-01-01) and stored in numeric variables.

The question makes therefore no sense in a SAS context.

For dates, you use the DAY, MONTH and YEAR functions to extract those numeric values from a date.

KyuL
Calcite | Level 5

Thanks for the explanation. I converted DOBC to character variable now the substr() works.

Tom
Super User Tom
Super User

SUBSTR() works on character variables. You defined DOBC as a numeric variable. 

 

If you give SUBSTR() a number it will first convert the number into a character string using the BEST12. format.  This will cause two problems with your code.  First dates are represented as number of days since 1960, so there are no digits that will look like month or year number.  Second is the values will have leading spaces since the number for today is 22,210 which only needs 5 digits, not 12.

KyuL
Calcite | Level 5

Thank you for the explanation.

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 1667 views
  • 0 likes
  • 3 in conversation