BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
texasmfp
Lapis Lazuli | Level 10

Hi:

 

I want to create a new field with a value determined by a formula applied to the character length of another field. 

 

The field, called targets, contains a series of three characters, separated by a space, except for the end (e.g., KOR TUR THA ITA VNM USA CHN IND FRA POL MEX MYS IDN).  In Excel the formula is easy: =(LEN(E2)+1)/4; where E2 is the cell referenced.  In the Excel formula, you simply add 1 to make up for the lack of a trailing blank and then divid by four to get the number of 3-character targets.  For that example, the value is 13.

 

There are hundreds of thousands of rows in the dataset with varying 3-character counts in each.

Is there a way to do that in SAS?  Thanks

1 ACCEPTED SOLUTION

Accepted Solutions
Patrick
Opal | Level 21

Are you eventually looking for the countw() function documented here?

data sample;
  string='KOR TUR THA ITA VNM USA CHN IND FRA POL MEX MYS IDN';
  n_terms=countw(string);
run;
proc print;
run;

Patrick_0-1594082822342.png

 

View solution in original post

5 REPLIES 5
Patrick
Opal | Level 21

Are you eventually looking for the countw() function documented here?

data sample;
  string='KOR TUR THA ITA VNM USA CHN IND FRA POL MEX MYS IDN';
  n_terms=countw(string);
run;
proc print;
run;

Patrick_0-1594082822342.png

 

ketpt42
Quartz | Level 8

You should be able to do the same:

value=(length(targets) + 1)/4;
Patrick
Opal | Level 21

@ketpt42 

Your formula won't work for an empty string.

data sample;
  string='KOR TUR THA ITA VNM USA CHN IND FRA POL MEX MYS IDN';
  n_terms=countw(string);
  n_terms2=(length(string) + 1)/4;
  n_terms3=lengthn(compress(string))/3;
  output;
  string=' ';
  n_terms=countw(string);
  n_terms2=(length(string) + 1)/4;
  n_terms3=lengthn(compress(string))/3;
  output;
  stop;
run;
proc print;
run;

Patrick_0-1594083425606.png

 

ketpt42
Quartz | Level 8
It wasn't clear from the information given that the value would ever be missing. Your solution was more elegant anyway.
sustagens
Pyrite | Level 9
Function countw counts words

hackathon24-white-horiz.png

The 2025 SAS Hackathon Kicks Off on June 11!

Watch the live Hackathon Kickoff to get all the essential information about the SAS Hackathon—including how to join, how to participate, and expert tips for success.

YouTube LinkedIn

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
  • 1482 views
  • 1 like
  • 4 in conversation