In this tutorial, we will show how to use the COUNTW Function in SAS, along with examples.
What does COUNTW Function do in SAS?
The COUNTW function is used in SAS to count the number of words in a character string.
Syntax of COUNTW Function
Below is the syntax of COUNTW Function in SAS.
COUNTW(string, [character(s)] , [modifier(s)])
string
: The character variable or string.character(s)
(optional): Delimiters that separate words.modifier(s)
(optional): Keywords that can change how the COUNTW function works.
Let's create a sample dataset for demonstration purpose.
data example; input string $60.; datalines; It's a pleasant day today I_am yet to receive payment 352+20+2=374 Send to my address xyz_a@gmail ; proc print; run;
Here we are using the COUNTW function to count the number of words in the variable "string".
data newdata; set example; count_words=countw(string); run;
By default SAS consider the followings as default delimiters:
blank ! $ % & ( ) * + , - . / ; < ^ |
In the example above it considered blank and + as delimiters to count the number of words.
In the COUNTW function, we can specify a delimiter which makes it to count the number of words based on the specified delimiter rather than the default one. In the example below, we are using blank space and underscore (_) sign as separators.
data newdata; set example; count_words=countw(string, ' '); count_words_=countw(string, '_'); run;
Below is an example where we are using the COUNTW function with the 'd' modifier. The 'd' modifier refers to digits. Here we are counting the number of words separated by digits.
data newdata; set example; count_words_digits=countw(string, , 'd'); run;
Important Note: You don't need to specify anything in the second argument when using the modifier.
Here is a list of modifiers that can be used in the COUNTW Function in SAS.
Modifier | Explanation |
---|---|
a | Adds alphabetic characters |
b | Counts from right to left instead of left to right |
c | Adds control characters |
d | Adds digits |
f | Adds an underscore and English letters |
g | Adds graphic characters |
h | Adds a horizontal tab |
i | Ignores the case of the characters (case-insensitive) |
k | Makes all characters that are not in the list to be treated as delimiters |
l | Adds lowercase letters |
m | It tells SAS that words that have a length of 0 |
n | Adds digits, an underscore, and English letters |
o | Considers the characters and modifier arguments only once |
p | Adds punctuation marks |
q | Ignores delimiters within substrings that are in quotation marks |
s | Adds space characters |
t | Trims trailing blanks from both the first and second argument |
u | Adds uppercase letters |
w | Adds printable characters |
x | Adds hexadecimal characters |
Share Share Tweet