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.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.