Search code examples
sasrenamesas-macrodo-loops

rename SAS variables in reverse order using do loops


I have 10 variables (var1-var10), which I need to rename var10-var1 in SAS. So basically I need var10 to be renamed var1, var9 var2, var8 var3, and so on.

This is the code that I used based on this paper, http://analytics.ncsu.edu/sesug/2005/PS06_05.PDF:

%macro new;

    data temp_one;
        set temp;

        %do i=10 %to 1 %by -1;
            %do j=1 %to 10 %by 1;
                var.&i=var.&j
            %end;
        %end;
        ;
%mend new;

%new;

The problem I'm having is that it only renames var1 as var10, so the last iteration in the do-loop.

Thanks in advance for any help!

Emily


Solution

  • You really don't need to do that, you can rename variable with list references, especially if they've been named sequentially.

    ie:

    rename var1-var10 = var10-var1;
    

    Here's a test that demonstrates this:

    data check;
        array var(10) var1-var10 (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        output;
    run;
    
    data want;
        set check;
        rename var1-var10 = var10-var1;
    run;
    

    If you do need to do it manually for some reason, then you need two arrays. Once you've assigned the variable you've lost the old variable so you can't access it anymore. So you need some sort of temporary array to hold the new values.