简体   繁体   English

如何在SAS中动态重命名变量?

[英]How to rename variables dynamically in sas?

I have a sas data set. 我有一个SAS数据集。 In it i have some variables following a pattern 在其中我有一些遵循模式的变量

 -W 51 Sales
 -W 52 Sales
 -W 53 Sales

and so on. 等等。

Now i want to rename all of these variables dynamically such that W 51 is replaced by starting date of that week and the new name becomes - 5/2/2013 Sales ? 现在,我想动态地重命名所有这些变量,以使W 51替换为该周的开始日期,新名称变为-5/2/2013 Sales

The reason i want to rename them is that i have sales data of all the 53 weeks in an year and the data set would be eassier for me to understand if i had the starting date of a week instead of W(week_no) Sales as a variable name 我想重命名它们的原因是,我拥有一年中所有53周的销售数据,并且该数据集对我来说更容易理解,如果我将一周的开始日期而不是W(week_no)销售为变量名

Is there any way i can do that in sas? 我有什么办法可以在sas中做到这一点?

You really don't want to rename your variables. 您确实不想重命名变量。 You may think you do, but it'll just bite you eventually. 您可能会认为自己做到了,但最终只会咬住您。

What you can do instead is give them descriptive labels. 可以做的是给他们提供描述性标签。 This can be done via proc datasets . 这可以通过proc datasets完成。

proc datasets library=<lib>;
    modify <dataset>;
    label <variable> '5/2/2013 sales';
run;

Just for fun lets assume you want to do this anyway -- Safest thing to do is just create a copy of the dataset for your output... 只是为了好玩,让我们假设您仍然想这样做-最安全的做法是为输出创建数据集的副本...

this code assumes your variable names are named like w1_sales and output names are going to be renamed to 03JAN2013_sale or something like that. 该代码假定您的变量名命名为w1_sales,并且输出名称将重命名为03JAN2013_sale或类似名称。

     data newDataSet; 
        set oldDataSet;

     %MACRO rename_vars(mdataset,year);
        data &mdataset.;
           set &mdataset.;
            %do i = 1 %to 53;
             %let weekStartDate = %sysfunc(intnx('week&i','01jan&year.'d,0));         %*returns the starting day of week(i) uses sunday as starting date.  If you want monday use 0.1 as last param;    
             %let weekstartDateFormatted =  %sysfunc(putn(&weekStartDate.,DATE.))     %*formats into ddMONyyy. substitute whatever format you want;
             rename w&i._Sale = &weekstartDateFormatted ._SALES;   
            %end;
          run;
    %MEND rename_vars;

    %rename_vars(newDataSet,2013);

I don't have time to test this right now, so sommebody let me know if I screwed it up somewhere. 我现在没有时间对此进行测试,所以sommebody让我知道我是否将其拧紧了。 This should at least get you going though. 不过,这至少应该可以帮助您。 Or you can send me or post some code to read a small sample dataset (obviously if this is possible without having to share some proprietary info. You might have to genericize it a bit) with those vars like that and I'll debug it. 或者,您可以给我发送或发布一些代码来读取一个小的示例数据集(显然,如果有可能不必共享一些专有信息。您可能必须对其进行泛化),然后使用此类var进行调试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM