DATA Step, Macro, Functions and more

Using the SUBSTRING function

Accepted Solution Solved
Reply
Regular Contributor
Posts: 199
Accepted Solution

Using the SUBSTRING function

I am trying to use the SUBSTRING function to extract a single character from a 60 character string. I want to create 60 new variables (D1, D2, etc.) each containing a sequential digit in the string. In other words, D1 contains the first digit of the string. D2 contains the second digit of the string. D3 contains the 3rd digit of the string, etc. There are multiple observations in the dataset.

 

My code is inadequate, but pasted below for reference. Thanks for any ideas you may have.

 

data want (drop=i);
set have;

array D(60);
array seq(60);

do i = 1 to 60;
D[i] = substr(seq[i], 1, 1);
* How do I write this so it will jump from the first position to the next position in the sequence automatically?
end;
run;

 


Accepted Solutions
Solution
‎08-08-2016 06:52 PM
Super User
Posts: 19,860

Re: Using the SUBSTRING function

Use the CHAR() function instead. 

 

CHAR(string, position)

String -> always the same

position -> loop counter, in this case i

 

SUBSTR(STRING, start, length)

 

String -> Should always be the same

Start -> loop counter, in this case i

length -> always 1.

 

D[i] = substr(STRING_VARIABLE, i, 1);

View solution in original post


All Replies
Solution
‎08-08-2016 06:52 PM
Super User
Posts: 19,860

Re: Using the SUBSTRING function

Use the CHAR() function instead. 

 

CHAR(string, position)

String -> always the same

position -> loop counter, in this case i

 

SUBSTR(STRING, start, length)

 

String -> Should always be the same

Start -> loop counter, in this case i

length -> always 1.

 

D[i] = substr(STRING_VARIABLE, i, 1);
Super User
Posts: 5,516

Re: Using the SUBSTRING function

One more item you might want to attend to ... assign a length to the new variables:

 

array D {60} $ 1;

 

Otherwise, the length of the new variables will default to the same length as the original incoming character string.

Super User
Super User
Posts: 7,988

Re: Using the SUBSTRING function

Could I ask why.  It is rarely beneficial to create many variables such as you are doing, in terms of programming.  For all your subsequent programming you then need to know how many there are, which could vary.  Are you doing some sort of agregates or maths on them, as you can probably do that straight from the string (or if necessary output one row per character).  Would make you life much easier.

☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 3 replies
  • 587 views
  • 3 likes
  • 4 in conversation