Hi community,
I don't know how to code this problem below. Any help is much appreciated!
Variable name fullname (length $30) has a respondent's first, middle, and last name. Create var shortname (length $20), which has only the first and last name, separated by a single blank.
You can use the LENGTH keyword in SQL to tell SAS how many bytes to use when storing the variable.
.... as shortname length=20
You could also have used the SUBSTR() function and SAS would have figured out that your expression could only return 20 bytes.
substr(....,1,20) as shortname
The SCAN() function ought to work here.
For example
SCAN(fullname,1) extracts the first "word" from fullname
Give it a try, see if you can get it to do what you want.
I tried it with sql and prxChange. It seems to work but I don't know how to specify length $20 for shortName.
data a; input fullname $30.; cards; George W. Bush George W Bush George Bush ; run; proc sql; select fullname, prxChange("s/(\w+\s)(\s*\w\.?\s+)(\w+)/\1\3/io",1,fullname) as shortName from a; quit;
You can use the LENGTH keyword in SQL to tell SAS how many bytes to use when storing the variable.
.... as shortname length=20
You could also have used the SUBSTR() function and SAS would have figured out that your expression could only return 20 bytes.
substr(....,1,20) as shortname
Tom, does SUBSTR actually use the length of $20? Admittedly it has been a long time since I tested this, but I recall that SUBSTR used the length of the incoming string to define a newly created variable. The basic idea was that the third parameter could be an expression instead of a hard-coded value, and so might not be capable of setting a length.
In a data step it will guess the length based on the input to the SUBSTR() function. But in SQL it will guess the length based on the output of the SUBSTR() function.
data x;
x=substr('1234567890',1,6);
y=vlength(x);
put y=;
run;
proc sql;
create table test1 as select substr('1234567890',1,6) as x from sashelp.class(obs=1);
quit;
data _null_;
set test1;
y=vlength(x);
put y=;
run;
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.