条件比较变量与数值

条件比较变量与数值

本文介绍了SAS 宏 if then 条件比较变量与数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多条路径的数据集,最后一个变量是遵循路径的人的频率.

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;

我想计算沿每条路径从前一站到后一站的频率,以计算它们各自的频率.因为有7站.会有49种组合,所以我写了一个宏代码.

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);

尽管代码本身没有问题,但无论我做什么,if 条件总是返回 false.例如,我希望在 do until 循环的第一次迭代中,if 条件为真,但返回为假.

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.

有人告诉我它与path&i=&f有关,是不是没有将path&i识别为变量名或其他什么?

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?

谢谢!

推荐答案

您将宏代码与数据步骤代码混淆了.

You're confusing macro code with data step code.

您需要使用 if 而不是 %if,例如.此外, %eval 也不会做你想做的事.这是一些经过改进的代码.

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;

%if 用于比较文本本身 - 所以它比较 path12,而不是 的值path1 变量.要获取变量的值,您必须使用常规的 if.%eval 也使用文本,而不是变量值,所以它在这里没有任何用处.

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;

现在,我认为这仍然是 0:因为它不能同时等于 2 和 5.您可能需要解决这个逻辑.

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 宏 if then 条件比较变量与数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:53