Hi,
I have a character variable called employment_flag of length 12 which either contains the values 1 or 0.
For example:
010000000010
011100100001
I want to find out the longest string of consecutive zeros between the first and last 1 for each value in this variable. For example, the answer for row 1 should be 8 and row 2 should be 4. Note that in example 2 we have a string of 2 zeros and 4 zeros but I'm interested in the longest string.
Any help is much appreciated!
Thanks
Hi @zishaq,
Here's another (but very similar) suggestion in view of the condition "between the first and last 1":
data have;
input c $12.;
cards;
010000000010
011100100001
;
data want;
set have;
do _n_=2 to countw(c,'1','m')-1;
m=max(m,lengthn(scan(c,_n_,'1','m')));
end;
run;
In case of less than two 1s in the string the above solution would (deliberately) return a missing value.
@zishaq wrote:
Hi,
I have a character variable called employment_flag of length 12 which either contains the values 1 or 0.
For example:
010000000010
011100100001
I want to find out the longest string of consecutive zeros between the first and last 1 for each value in this variable. For example, the answer for row 1 should be 8 and row 2 should be 4. Note that in example 2 we have a string of 2 zeros and 4 zeros but I'm interested in the longest string.
Any help is much appreciated!
Thanks
One way:
data example;
input x :$12.;
longest=0;
do i=1 to countw(x,'1');
longest = max(longest, length(scan(x,i,'1')));
end;
drop i;
datalines;
010000000010
011100100001
;
The above code treats the 1 as delimiter for both the countw and scan functions to break the string up into "words" consisting of only 0 and uses the length function to return the number of characters.
Hi @zishaq,
Here's another (but very similar) suggestion in view of the condition "between the first and last 1":
data have;
input c $12.;
cards;
010000000010
011100100001
;
data want;
set have;
do _n_=2 to countw(c,'1','m')-1;
m=max(m,lengthn(scan(c,_n_,'1','m')));
end;
run;
In case of less than two 1s in the string the above solution would (deliberately) return a missing value.
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
Still thinking about your presentation idea? The submission deadline has been extended to Friday, Nov. 14, at 11:59 p.m. ET.
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.
Ready to level-up your skills? Choose your own adventure.