In SAS use loop to rename indexed columns?

2019-05-03 08:34发布

问题:

I have a dataset with variables as col1, col2, col3, ..., col15. I want to rename them to new1, new2, new3, ..., new 15. I can write 15 times the similar rename col1 = new1; in SAS but how can I achieve this using loop? Thanks.

回答1:

Firstly, it's not clear whether you're talking about the rename statement in proc datasets or in the data step. If you don't need to do anything else to the data, you should definitely use proc datasets to do this, because otherwise (in a data step) you're unnecessarily reading/writing every record in the dataset, just to alter variable names.

If you are using the data step, just use

rename col1-col15=new1-new15;

I'm not sure if you can use that shortcut in proc datasets. Which brings us to your looping question. Unless you're doing this lots of times or dynamically, it's probably just as easy to copy/paste the code 15 times. Here's a way to generate the statement you want, put it in a macro variable, and use that macro variable in the rename statement:

data _null_;
  length myVar $ 1000;
  *myVar='';
  do i=1 to 15;
    myVar=catx(' ',myVar,' ',cats('col',i,'=','new',i));
  end;
  call symput('rename',myVar);
run;

%put &rename;

proc datasets library=mylibrary;
  modify mydataset;
  rename &rename;
run;


回答2:

Here's a way to do it in the case that your variable names fit a nice, easy naming pattern:

 DATA out;
 SET  in;
 ARRAY oldnames (15) col1-col15;
 ARRAY newnames (15) new1-new15;
 DO i = 1 TO 15;
      newnames(i) = oldnames(i) ;
 END;
 RUN;

Or, more generically:

 DATA out;
 SET  in;
 ARRAY oldnames (4) abc def ghi jkl ;
 ARRAY newnames (4) mno pqr stu vwx ;
 DO i = 1 TO 4;
      newnames(i) = oldnames(i) ;
 END;
 RUN;


标签: sas