Hi,
can you please provise me solution of follwing problem.
I want to count no of words from following data with the help of do loop only (do not use COUNTW function ).
data a;
input name $ 1-30;
datalines;
i am vinayak more
asif shaikh is my friend
;
run;
output should be like this:
name count
i am vinayak more 4
asif shaikh is my friend 5
The below code would also take care if there are multiple blanks
data a;
input name $ 1-30;
datalines;
i am vinayak more
asif shaikh is my friend
;
run;
data new(drop = len c char_val last_char_val);
length last_char_val $1. ;
retain last_char_val;
set a;
len=length(name);
c=1;word_count=0;
do while(c<=len);
char_val=substr(name,c,1);
if char_val eq ' ' and last_char_val ne ' ' then word_count +1;
c+1;
last_char_val=char_val;
end;
word_count +1;
run;
There can be many ways...below mentioned is counting of blanks by compressing blank.
data new;
set a;
word_count=length(name) - length(compress(name)) +1 ;
run;
The below code would also take care if there are multiple blanks
data a;
input name $ 1-30;
datalines;
i am vinayak more
asif shaikh is my friend
;
run;
data new(drop = len c char_val last_char_val);
length last_char_val $1. ;
retain last_char_val;
set a;
len=length(name);
c=1;word_count=0;
do while(c<=len);
char_val=substr(name,c,1);
if char_val eq ' ' and last_char_val ne ' ' then word_count +1;
c+1;
last_char_val=char_val;
end;
word_count +1;
run;
Why you post it at IML forum, Another DO LOOP is using CALL PRXNEXT().
data a;
input name $ 1-30;
datalines;
i am vinayak more
asif shaikh is my friend
;
run;
data want;
set a;
i=1;count=0;
temp=scan(name,i);
do while(not missing(temp));
count+1;
i+1;
temp=scan(name,i);
end;
drop i temp;
run;
OK. I just figure out IML way.
data a;
input name $ 1-30;
datalines;
i am vinayak more
asif shaikh is my friend
;
run;
proc iml;
use a;
read all var{name};
close;
count=j(nrow(name),1,0);
do i=1 to nrow(name);
token=substr(name[i],1:length(name[i]),1);
count[i]=sum(token=' ')+1;
end;
print name count;
quit;
And why "don't use countw"? I would think that a function specifically designed and written for the purpose would be better than any other solution?
Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!
Learn how to run multiple linear regression models with and without interactions, presented by SAS user Alex Chaplin.
Find more tutorials on the SAS Users YouTube channel.