Learning SAS? Welcome to the exclusive online community for all SAS learners.

Counting number of characters in a string for each respondent

Accepted Solution Solved
Reply
Occasional Contributor
Posts: 13
Accepted Solution

Counting number of characters in a string for each respondent

Hello! 

I have a variable which is a string (currently numeric, though I imagine it might be best to change this to a character format) of numbers. I need to create a flag for any responses that have an odd number of characters. This is not a flag for odd numbers but for the number of characters. I need this for each respondent and not for one individual. 

 

My question: How can I create a code for counting the number of characters in a string? (E.g. 102 = 3, 10879 = 5, etc.)  From there, I can create the flag. For some reason I am just struggling with finding the right code for counting what I need. 

 

Thanks! 


Accepted Solutions
Solution
‎07-11-2016 10:31 AM
Respected Advisor
Posts: 4,641

Re: Counting number of characters in a string for each respondent

Math to the rescue!

 

/* Assuming the numbers are positive integers */
data have;
input number;
datalines;
102
10879
23
543
12
;

data want;
set have;
digits = 1 + int(log10(number));
oddDigits = mod(digits, 2);
run;

proc print; run;
PG

View solution in original post


All Replies
Trusted Advisor
Posts: 1,204

Re: Counting number of characters in a string for each respondent

Hi,

 

Please try this.

 

data have;
input number;
datalines;
102
10879
23
543
12
;

data want;
set have;
length flag $8.;
if mod(length(strip(put(number, 8.))),2) ne 0 then flag='odd';
else flag='even';
run;

Super User
Posts: 17,781

Re: Counting number of characters in a string for each respondent

Functions to the rescue! 

 

Length provides the length of the string. 

 

Mod(num,2) = 0 can be used to test if a number is even or odd. If a number is divisible by 2 it's even otherwise odd. 

 

The code from @stat_sas looks correct. 

Solution
‎07-11-2016 10:31 AM
Respected Advisor
Posts: 4,641

Re: Counting number of characters in a string for each respondent

Math to the rescue!

 

/* Assuming the numbers are positive integers */
data have;
input number;
datalines;
102
10879
23
543
12
;

data want;
set have;
digits = 1 + int(log10(number));
oddDigits = mod(digits, 2);
run;

proc print; run;
PG
Occasional Contributor
Posts: 13

Re: Counting number of characters in a string for each respondent

Thank you so much - this is exactly what I needed. 

☑ This topic is SOLVED.

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

Discussion stats
  • 4 replies
  • 1403 views
  • 6 likes
  • 4 in conversation