Search code examples
sassubstr

Create new variable using partial string of another variable in SAS


I am new to SAS and would like to keep what's before the hyphen '-' to create a new variable:

 x 
abc-something
efgh-everything
hij-something

I tried:

DATA NEW 
    set OLD;
    y = (compress(substr([x], 3, 1));
RUN;
PROC PRINT DATA = NEW; 
RUN; 

to get it to look like this but it doesn't work:

 x 
abc
efgh
hij

Solution

  • Use the scan() function to split a string based on delimiter character(s).

    y=scan(x,1,'-');
    

    Of if you just want to first three characters then use SUBSTR() function.

    y=substr(x,1,3);