Help using Base SAS procedures

Expression in an observation

Reply
N/A
Posts: 1

Expression in an observation

Hi,

I have a dataset that contains, let's say, a text variable 'Operation' that contains operations on other columns (i.e. each observation is a different operation). For example, if the first obs. of 'Operation' is A+B, I would like then to add the columns A and B. If the second obs is 2*(C+D), then I want to add coluns C and D and multiply by two, and so on. So what I need is a datastep line that looks like this: result=('the content of 'Operation'). I tried a Call Execute but I can't make it work. Is there an easy solution to that problem?

Thanks for your help,

Nancy
Respected Advisor
Posts: 4,173

Re: Expression in an observation

Hi Nancy

An approach like in the code below could work for you.

data have;
infile datalines dsd dlm=';' truncover;
informat operations $40. a b c d 8.;
input operations a b c d;
datalines4;
a*b;1;2;3;4
2*(c*d);1;2;3;4
a*b;1;2;3;4
a+b+c;1;2;3;4
;;;;
run;

proc sort data=have;
by operations;
run;

filename gencode temp;

data have;
set have end=last;
by operations;

file gencode;
/* file print;*/
if _n_=1 then
do;
put ' select(case);';
end;
if first.operations then
do;
case+1;
put ' when (' case +(-1) ') do;';
put ' result=' operations ';';
put ' end;';
end;
if last then
do;
put ' end;';
end;
run;

data want;
set have;
%include gencode;
run;

proc print data=want;
run;


HTH
Patrick
Super Contributor
Super Contributor
Posts: 365

Re: Expression in an observation

Hello Nancy,

You can also use the following macro approach:

data have;
infile datalines dsd dlm=';' truncover;
informat op $40. a b c d 8.;
input op a b c d;
datalines4;
a*b;1;2;3;4
2*(c*d);1;2;3;4
a*b;1;2;3;4
a+b+c;1;2;3;4
;;;;
run;

/* Putting ops into macro variables */;
proc SQL;
select count(*) as n into :n from have;
%let n=%TRIM(&n);
select op as o into Smiley Surprised1-Smiley Surprised&n from have
;quit;

/* Using macro variables as operations */;
%macro a;
%local i;
data want;
set have;
%do i=1 %to &n;
if _n_=&i then result=&&o&i;
%end;
run;
%mend a;
%a

Sincerely,
SPR
Ask a Question
Discussion stats
  • 2 replies
  • 106 views
  • 0 likes
  • 3 in conversation