I have input data set : have.
I want to remove special char from Type Variable and if There are two type in One row, then second type should be shift to next row associated with Same ID.
Looking for below output in want dataset.
ID Type
1 T
2 KO
2 W
3 3
3 K3
4 R
5 LBL
6 LBL
7 G
8 S
data have ; infile datalines dlm=' ' dsd; Input ID $ type $; datalines; 1 ^T 2 ^KO|^W 3 ^3|K3 4 ^R 5 ^LBL 6 ^LBL 7 ^G 8 ^S ; run
With regular expressions:
data want;
if not prxId then prxId + prxParse("/\w+/");
set have;
start = 1; stop = length(type);
call prxnext(prxID, start, stop, type, position, length);
do while (position > 0);
newType = substr(type, position, length);
output;
call prxnext(prxID, start, stop, type, position, length);
end;
drop prxId start stop position length;
rename newType=type;
run;
Please try the below code
data want;
set have;
if scan(type,1,'|') ne '' then type2=scan(compress(type,'^'),1,'|');
output;
if scan(type,2,'|') ne '' then do;
type2=scan(compress(type,'^'),2,'|');
output;
end;
run;
data have ;
infile datalines dlm=' ' dsd;
Input ID $ type $;
datalines;
1 ^T
2 ^KO|^W
3 ^3|K3
4 ^R
5 ^LBL
6 ^LBL
7 ^G
8 ^S
;
run;
data want;
set have;
do _n_=1 to countw(type,'|');
need=compress(scan(type,_n_,'|'),,'cp');
output;
end;
drop type;
run;
How do we know where one type starts or ends? You really should tell us that you want to split at the | character instead of making us guess.
One way:
data have ; infile datalines dlm=' ' dsd; Input ID $ type $; do i= 1 to countw(type,'|'); newtype = compress(scan(type,i,'|'),'','ADK'); output; end; drop i; datalines; 1 ^T 2 ^KO|^W 3 ^3|K3 4 ^R 5 ^LBL 6 ^LBL 7 ^G 8 ^S ; run
With regular expressions:
data want;
if not prxId then prxId + prxParse("/\w+/");
set have;
start = 1; stop = length(type);
call prxnext(prxID, start, stop, type, position, length);
do while (position > 0);
newType = substr(type, position, length);
output;
call prxnext(prxID, start, stop, type, position, length);
end;
drop prxId start stop position length;
rename newType=type;
run;
Thanks @PGStats - This is the way I was looking for, in regular expression, logic is more dynamic if we get some other special char as well.
Thanks others as well for trying it and giving your best sol.
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.