BookmarkSubscribeRSS Feed
CathyVI
Pyrite | Level 9

I am trying to check the length of a certain character variable. I have a variable id_Settings which all values should have a length of 8 e.g. CA455006. How do i use the length statement to check if all my observations in the ID_settings have the required length ?

 

Basically, how do I use length statement to check the length of variable ID_setting?

 

I have sample data but the original data has over 2 million encounters.

 

data check;
input Name $ 1-5 ID_setting $ 7-15;
datalines;
Dog   DO123232
Cat   CA345566
Mouse MO987973
Dog   DO468579
Owl   OW576864
Cat   CA089854
run;

 

Thanks,

5 REPLIES 5
PaigeMiller
Diamond | Level 26

I think you don't mean the length of the character variable, I think you mean the length of the text string in each observation. These are not the same.

 

In that case, you use the LENGTH function.

data check;
input Name $ 1-5 ID_setting $ 7-15;
l=length(id_setting);
datalines;
Dog   DO123232
Cat   CA345566
Mouse MO987973
Dog   DO468579
Owl   OW576864
Cat   CA089854
;

 

--
Paige Miller
CathyVI
Pyrite | Level 9
@PaigeMiller, Yes, you are right i mean the length of the text string in each observation. Thank you.
Reeza
Super User
A length STATEMENT sets the maximum possible length for a character variable. The length FUNCTION returns the number of characters in a variable.

You want the length function, length().

data want;
set have;
length_ID = length(ID_Setting);
run;

*see the different values;
proc freq data=want;
table length_id;
run;

*find anything not 8.
data not8;
set want;
where length_id ne 8;
run;
CathyVI
Pyrite | Level 9
@Reeza: Thank you! This works.
ChrisNZ
Tourmaline | Level 20

Actually, you might prefer function lengthn()  since function length()  will not let you know if you have empty strings.

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 5 replies
  • 754 views
  • 2 likes
  • 4 in conversation