BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
lioradam
Quartz | Level 8

Hello,

I have variables with observations in different lengths as 000R201806, ZY201906

and I want to separate it into the letters (or digits) at the beginning of the string, the year, and the month: 

000R     2018    04

ZY         2019    06

 

What code can I use?

 

Thank you,

Lior

1 ACCEPTED SOLUTION

Accepted Solutions
Tom
Super User Tom
Super User

@lioradam wrote:

Hello,

I have variables with observations in different lengths as 000R201806, ZY201906

and I want to separate it into the letters (or digits) at the beginning of the string, the year, and the month: 

000R     2018    04

ZY         2019    06

 

What code can I use?

 

Thank you,

Lior


SUBSTR(). 

Note that it might be simpler to just create a DATE value instead of separate YEAR and MONTH values.

data have;
  input string $20.;
cards;
000R201806
ZY201906
;

data want;
  set have;
  date = input(substrn(string,length(string)-5),yymmn6.);
  format date yymmdd10.;
  short_string=substr(string,1,length(string)-6);
  year=year(date);
  month=month(date);
run;

Result:

                                   short_
Obs      string            date    string    year    month

 1     000R201806    2018-06-01     000R     2018      6
 2     ZY201906      2019-06-01     ZY       2019      6

View solution in original post

6 REPLIES 6
PaigeMiller
Diamond | Level 26

Always two digits for the month, four digits for the year, and the rest is the 'beginning of the string'?

--
Paige Miller
lioradam
Quartz | Level 8

Yes

PaigeMiller
Diamond | Level 26

Looks like @Tom beat me to it, but really you just need the length of the string, and then the last 6 characters are the year/month, and the rest are the "beginning of the string".

--
Paige Miller
lioradam
Quartz | Level 8

Thank you 👍

Tom
Super User Tom
Super User

@lioradam wrote:

Hello,

I have variables with observations in different lengths as 000R201806, ZY201906

and I want to separate it into the letters (or digits) at the beginning of the string, the year, and the month: 

000R     2018    04

ZY         2019    06

 

What code can I use?

 

Thank you,

Lior


SUBSTR(). 

Note that it might be simpler to just create a DATE value instead of separate YEAR and MONTH values.

data have;
  input string $20.;
cards;
000R201806
ZY201906
;

data want;
  set have;
  date = input(substrn(string,length(string)-5),yymmn6.);
  format date yymmdd10.;
  short_string=substr(string,1,length(string)-6);
  year=year(date);
  month=month(date);
run;

Result:

                                   short_
Obs      string            date    string    year    month

 1     000R201806    2018-06-01     000R     2018      6
 2     ZY201906      2019-06-01     ZY       2019      6
lioradam
Quartz | Level 8

Thank you very much!

 

Regards,

Lior