Today, I will demonstrate one of those tricks that you will rarely need. However, when you do need it, it is a real treat. Once in a while, you may see a character variable, that forms an arithmetic expression in the SAS Data Step. like expr = ‘2.5*2**2+1’. Now, imagine that you want to evaluate the expression in the data step. If the expression was outside the data step and in a macro variable, this is easy right? Simply do:

%let expr = 2.5*2**2+1;
%let num = %sysevalf(&expr);
%put &num.;

The result is 11. However, in a data step, this is not that easy. This post demonstrates a neat workaround to evaluate an arithmetic expression stored in a character variable during data step execution using the Resolve Function and the %Sysevalf Macro Function.

A SAS Data Step Example

Now, let us look at the same example from within the data step. First, let us clarify why the approach above will not work directly. Macro code and macro functions such as %sysevalf execute before the data step even begins compiling. Therefore they do not work on PDV variables. Because the PDV does not even exist yet. With a little care though, we can use the same logic within the data step.

First of, we trick the SAS macro scanner by placing the entire %Sysevalf Function call in single quotes. Remember the word scanner does not tokenize within single quotes. That is the reason why macro variables are not resolved within single quotes. Only within double quotes.

Next, the Resolve Function enables us to execute macro language elements during the execution phase of the Data Step. So when the Resolve Function executes, the %Sysevalf Function executes and performs the calculation. Just like the simplified example above. Finally, the SAS Resolve Function returns a character value. Therefore, I use the Input Function to Convert the result to a numeric value.

data test;
   expr = '2.5*2**2+1';
   num  = input(resolve('%sysevalf(||'expr'||)'), 8.);
run;

As expected, the num variable takes the correct value of 11.

Summary

In this post, I demonstrate how to use evaluate an arithmetic expression stored in a character variable in the SAS Data Step. The trick is to use the %Sysevalf and Resolve Function and delay the execution of the %Sysevalf Function. As with most macro code, the key to success is to understand the timing of compilation and execution. If you want to learn more about macro timing, I recommend the book Carpenter’s Complete Guide to the SAS Macro Language, Third Edition. Worth every penny and more.

For related posts, see Explore the %Eval Macro Function in SAS, Explore the Parmbuff Option in the SAS Macro Language and 5 SAS Macro Quoting Functions You Should Know.

You can download the entire code from this post here.