Extracting first letter of each word in SAS Programming

Viewed 36
data have;
input full_names 50.;
datalines;
Austin Richard Post
Quavious Keyate Marshall
David John McDonald
Jonathan Lyndale Kirk
;
run;

Required output first letter of each word as follows

ARP QKM DJM JLK

2 Answers

Something that works regardless of the number of names.

  • COUNTW to determine the number of words
  • CATT to concatenate the first initials

FYI - your sample data step is incorrect and does not run as posted.

data initials;
set have;
nwords = countw(full_names);
length initials $8.;

initials = '';
do i=1 to nwords;
   initials = catt(initials, substr(scan(full_names, i), 1, 1));
end;

drop i nwords;
run;

This should work. Also, you have an error in data have, as you have a character variable, not numeric one (and you declared numeric one).

data have;
input full_names $50.;
datalines;
Austin Richard Post
Quavious Keyate Marshall
David John McDonald
Jonathan Lyndale Kirk
;
run;

data want;
    set have;
    first_letters=cats(substr(scan(full_names,1),1,1),substr(scan(full_names,2),1,1),substr(scan(full_names,3),1,1));
run;
Related