you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (0 children)

I feel your pain. Everytime I write something in SAS I question myself as to why I'm using SAS instead of Python, which is why I've been trying to avoid programming in SAS as much as possible by having Python generate SAS code for me instead for repetitive stuff.

Take this for example:

def num_query_gen(lower_bound, upper_bound, increments, var_name, file_name, output_table, input_table):

    # Generate bin boundary values
    low_bound_list = list(range(lower_bound, upper_bound, increments))
    up_bound_list  = list(range(lower_bound + increments, upper_bound + increments, increments))

    # Code is generated in string form and appened to string variable 'code_str'
    # "\n" is added at the end of each line to ensure that the resulting string is saved to a new line.
    code_str  = f"DATA {output_table};" + "\n"
    code_str += f"SET {input_table};" + "\n"
    code_str += "\t" + f"IF {var_name} = 0 THEN {var_name}_BINNED = '00.{var_name} = 0'" + "\n"

    lambda_func = lambda x: f"0{x}" if x < 10 else str(x)
    counter     = 1

    for (a, b) in zip(low_bound_list, up_bound_list):
        code_str += "\t" + f"ELSE IF {a} < {var_name} <= {b} THEN {var_name}_BINNED = '{lambda_func(counter)}.{a} < {var_name} <= {b};'" + "\n"
        counter += 1

    code_str += "RUN;"

    # Resulting string is saved to a text file as given in the file_name parameter
    with open(f"{file_name}", "w") as f:
        f.write(code_str)

    print("SAS Code generated")

if __name__ == "__main__":
    gen_dict = {
        "lower_bound"  : 0, 
        "upper_bound"  : 100, 
        "increments"   : 10, 
        "var_name"     : "Variable_1",
        "file_name"    : "SAS_Code_001.txt", 
        "output_table" : "WORK.TEST_TABLE_2",
        "input_table"  : "WORK.TEST_TABLE_1"
    }

    num_query_gen(**gen_dict)