SAS macro if then condition compare variable with

2019-02-28 08:36发布

问题:

I have a data set that include several paths and the last variable is the frequency of the people following the path.

data path;
input path1 path2 path3 path4 path5 path6 frequency;
cards;
2 5 3 6 7 2 465
4 3 2 3 0 0 20394
2 1 3 6 5 0 309
1 3 2 6 5 3 302
2 2 5 4 7 7 6783
;
run;

I would like to calculate the frequency from the former stop to the latter stop along each path to count their individual frequency. since there are 7 stops. there will be 49 combinations, so I wrote a macro code.

%macro count(name,f,l);
data path;
    set me.path;
    retain &name;
    &name=0;
    %let i=0;
    %do %until (&i=6);
        %let i = %eval(&i+1);
        %if path&i=&f and path&i=&l %then &name=%eval(&name+frequency);
    %end;
run;
%mend;

%count(P2t5,2,5);

although the code itself presents no problem, the if condition always returns false no matter what I do. for example, I would expect in the first iteration of the do until loop, the if condition will be true, but it returns as false.

Something tells me it has to do with the path&i=&f, is it not recognizing the path&i as a variable name or something else?

Can anyone solve this problem for me please?

Thanks!

回答1:

You're confusing macro code with data step code.

You need to use if not %if, for one. Also, %eval won't do what you want either. Here's some code with some improvements.

%macro count(name,f,l);
data path;
    set me.path;
    retain &name;
    &name=0;
    %do i=1 %to 6;
        if path&i=&f and path&i=&l then &name=&name+frequency;
    %end;
run;
%mend;

Macro %if is used for comparing the text itself - so it compares path1 to 2, not the value of the path1 variable. To get the value of a variable you have to use regular if. %eval also uses the text, not the variable values, so it will do nothing useful here.

You actually don't need a macro loop for this. Normally we would use arrays. I do assume you want the other parts in macro though...

%macro count(name,f,l);
data path;
    set me.path;
    retain &name;
    array path[6];
    &name=0;
    do i=1 to 6;
        if path[i]=&f and path[i]=&l then &name=&name+frequency;
    end;
run;
%mend;

Now, I think this is always 0 still: because it can't be equal to 2 and 5 at the same time. That logic you may need to address.



标签: sas sas-macro