Create a new variable last name from name, find the starting position of first and create new variable first name from name variable using the positions found in previous question.Hint: Use SUBSTR function
Post the code and log you already have, and show where it does not meet your expectations.
DATA PART_A ;
SET LEARN.DEPARTMENT(KEEP = NAME) ;
LAST_NAME = SCAN(NAME,1);
RUN ;
DATA PART_B;
SET LEARN.DEPARTMENT (KEEP = NAME);
NAME = COMPRESS(NAME,,'P') ;
FIRST_NAME = SCAN(NAME,2,'');
CHAR = SUBSTR(FIRST_NAME,1,1) ;
IF INDEX(CHAR,'') > 0 ;
RUN ;
Hi Kurt,
Part a is done by me but in second part I've tried to find the starting position of first name as mentioned below but not able to do the same.
DATA PART_B;
SET LEARN.DEPARTMENT (KEEP = NAME);
NAME = COMPRESS(NAME,,'P') ;
FIRST_NAME = SCAN(NAME,2,'');
CHAR = SUBSTR(FIRST_NAME,1,1) ;
IF INDEX(CHAR,'') > 0 ;
RUN ;
Here's code that does what I think you want, retrieving first_name in two ways:
data department;
infile '$HOME/sascommunity/department.csv' dlm=',' dsd termstr=CRLF firstobs=2;
input code_id $ department :$30. expenditure :comma. name :$30.;
run;
data want;
set department (keep=name);
last_name = scan(name,1,',');
first_name = left(scan(name,2,','));
first_name = substr(first_name,1,length(first_name)-2);
start_pos = indexc(name,',') + 2;
first_name_2 = substr(name,start_pos);
run;
The additional substr in
first_name = substr(first_name,1,length(first_name)-2);
removes the country code.
I am not sure, if I understood the requirement correctly, but as far as i understood this is the solution :
data new;
set department;
last_name= scan(names,2,',');
pos=indexc(names,',');
first_name = substr(names,1,pos-1);
drop pos;
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.