Hello
I want to find first location of character in string.
Lets say I have the following data.
Vector='0,0,5,11,9,10'
I want to find the first location (after comma) where the number is different than 0.
In this case the answer is 3 because the third argument in vector has value different than 0.
How can I calculate it in SAS please?
thanks
Ronein
data want (drop=i); Vector='0,0,5,11,9,10'; do i=1 to countw(vector,','); if input(scan(vector,i,','),best.) > 0 and word = . then word=i; end; run;
@RW9's code with a tweak to stop looping once a word has been found.
data want (drop=_:);
Vector='0,0,5,11,9,10';
_n=countw(vector,',');
do _i=1 to _n;
if input(scan(vector,_i,','),best.) > 0 then
do;
word=_i;
leave;
end;
end;
run;
Quite true, but then you would only need:
data want; vector='0,0,5,11,9,10'; do word=1 to countw(vector,','); if input(scan(vector,word,','),best.) > 0 then leave; end; run;
As word gets incremented up to the point where the loop is exited.
And what's the value of Word if the condition never gets True?
True, I had assumed there would always be one non-zero.
This is one of the occasions where PRX is really good:
data want;
Vector='0,0,5,11,9,10';
pos=prxmatch('/\b[1-9]/',Vector);
run;
A short explanation of the search string: \b means a word boundary (could be your comma, or the beginning of the string), [1-9] means one of the digits 1 to 9. If there is no match, the function returns 0.
@s_lassen wrote:
This is one of the occasions where PRX is really good:
data want; Vector='0,0,5,11,9,10'; pos=prxmatch('/\b[1-9]/',Vector); run;
A short explanation of the search string: \b means a word boundary (could be your comma, or the beginning of the string), [1-9] means one of the digits 1 to 9. If there is no match, the function returns 0.
...except that it returns 5 instead of 3. The OP asks for the number of the Word (3rd word) and not the start position in the string.
Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.
Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.
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.