DATA Step, Macro, Functions and more

scan function

Reply
Frequent Contributor
Posts: 82

scan function

I have a data similar to these:

data data;
input value $ name $15.;
datalines;
4.1% abc 4.1% a
3.2% a2 b c 3.2%
1.5% ab.cd 1.5% a ab
;
run;

What I need to do is to make a new variable from variable „name” keeping only beginning of it till the numbers with followed with % sign (that are as separate variable „value” here). So I would like to have values: abc, a2 b c, ab.cd. As the number of characters are different and also name includes special characters and spaces, I think it isn’t possible to use simple substr or scan functions.

So what I tried to do is to create macro variable that countains these values:
proc sql noprint;
select value into: val_list separated by ' ' from data;
quit;
%put &val_list;

After that I use this macro variable, scanning values one by one and want to use scan function to ask SAS to make a new variable „changed_name” keeping only values before those symbols that are in value read from macro variable &var_leave.

%macro calc;
data test;
set data;
format macronum $8.;

%let num=1;
%let var_leave=%scan(&val_list,&num , %str( ));
%do %while (&var_leave ne);
if &num=_n_ then do;

macronum="&var_leave";
changed_name=scan(name,1, "&var_leave");

output;
end;

%let num=%eval(&num+1);
%let var_leave=%scan(&val_list,&num);
%end;
run;
%mend;
%calc;

Of course, that doesn‘t work Smiley Happy As I understand defining macro variable works as expected, but scan function later doesn‘t do what I wanted.

Maybe you could advice me where is the error in my codes or suggest some better way to do this task?
Regular Contributor
Posts: 171

Re: scan function

Here is one way to solve the problem just by using substr, find, and anyspace functions:
[pre]
data data;
input value $ name $15.;
datalines;
4.1% abc 4.1% a
3.2% a2 b c 3.2%
1.5% ab.cd 1.5% a ab
;
run;

data data1;
set data;
name1=substr(name, 1, anyspace(substr(name, 1, find(name, '%')-1), -1*(find(name, '%')-1)));
run;

proc print data=data1;
run;

[/pre]
Regular Contributor
Posts: 171

Re: scan function

Actually, now that I think about it, it would be even better to use the anyalpha function instead of the anyspace function, just in case there is no space between the character and the number. Message was edited by: polingjw
Frequent Contributor
Posts: 82

Re: scan function

Thanks, it works perfectly! Smiley Happy
Ask a Question
Discussion stats
  • 3 replies
  • 144 views
  • 0 likes
  • 2 in conversation