Stephane Maarek
Stephane Maarek

Reputation: 5352

Create a SAS function that takes as input and output a dataset

I am doing the same 10 sub steps transformation to multiple data sets. Let's call this transformation flag_price_change.
This transformation takes as an input a dataset and a threshold (real) and creates 10 subdatasets in order to come up with the final one with some added columns. As I said before, I repeat this transformation to multiple datasets

As I am processing multiple data tables the same way, I would like to know if I could create a function like this in SAS.

flag_price_change(input_table,column_name1,column_name2,threshold,output_table).

Where column_name 1 and 2 are just names of the columns the algorithm just focus on, and output_table should be the created table after the flag_price_change function is executed.

Questions:

  1. What's the procedure to define such a function?
  2. Can I store it in a separate SAS file?
  3. How do I call this function from another SAS program?

Upvotes: 1

Views: 359

Answers (1)

MDe
MDe

Reputation: 2508

SAS functions are for individual observations of data. What you want is a macro (check out a starter guide here), which is defined like this:

%macro flag_price_change(input_table, column_name1, column_name2, threshold, output_table);
    /** Inside the macro, you can refer to each parameter/argument 
        with an ampersand in front of it. So for example, to add
        column_name1 to column_name2, you would do the following:
    **/

    DATA &output_table;
        set &input_table;

        new_variable = &column_name1 + &column_name2;
    RUN;

%mend;

To call the macro, you would do this:

%flag_price_change(
    input_table = data1, 
    column_name1 = var1, 
    column_name2 = var2, 
    threshold    = 0.5, 
    output_table = output1);

To call the same code on another data set with different variable names and threshold:

%flag_price_change(
    input_table = data2, 
    column_name1 = var3, 
    column_name2 = var4, 
    threshold    = 0.25, 
    output_table = output2);

There are a lot of tricks and catches with macro programming to be aware of, so do check your work at each step.

Upvotes: 2

Related Questions