BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
Ronein
Onyx | Level 15

Hello

Here is a code to split a char column to multiple columns.

In this code I know in advance that there are maximum 4  words in the string.

My question is How can I modify the code that it will calculate automatically the maximum number of words.

 

data cars_parse;
 set sashelp.cars;
 array modelname[5] $15 model1-model5;
 do i = 1 to 5;
  modelname[i] = scan(model,i,", ");
 end;
 keep model model1-model5;
run;

1 ACCEPTED SOLUTION

Accepted Solutions
Shmuel
Garnet | Level 18

you can combine the first two steps in one data step:

data tbl1;
 set sashelp.cars  end=eof;
       retain numWords 0;
       delims = ' ,.!';                 /* delimiters: space, comma, period, ... */
       numWords = max(numWords , countw(str, delims));    
                            /* for each line of text, how many words? */
       if eof then call symput('No_words', left(numWords));
Run;
 

View solution in original post

3 REPLIES 3
Shmuel
Garnet | Level 18

Use function COUNTW()

Ronein
Onyx | Level 15

Thanks.

Will it work well now or we can do it with one step only?

data tbl1;
 set sashelp.cars;
delims = ' ,.!';                 /* delimiters: space, comma, period, ... */
numWords = countw(str, delims);       /* for each line of text, how many words? */
Run;


Proc SQL noprint;
select  max(numWords)  into   :No_words
 from tbl1;  
quit;
 

Data desired;
Set sashelp.cars;
 array modelname[&No_words.] $15 model1-model& No_words.;
 do i = 1 to & No_words.;
  modelname[i] = scan(model,i,", ");
 end;
 keep model model1-model& No_words.;
run;
Shmuel
Garnet | Level 18

you can combine the first two steps in one data step:

data tbl1;
 set sashelp.cars  end=eof;
       retain numWords 0;
       delims = ' ,.!';                 /* delimiters: space, comma, period, ... */
       numWords = max(numWords , countw(str, delims));    
                            /* for each line of text, how many words? */
       if eof then call symput('No_words', left(numWords));
Run;
 

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

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
  • 3 replies
  • 9981 views
  • 2 likes
  • 2 in conversation