SAS - 根据另一个数据集

时间:2016-07-18 07:34:32

标签: sas

我正在使用SAS,我有一个名为a_17,a_18,a_19,...,a_27的变量数据集。我也有像这样的数据集

id  name
17  SDDF COCONUT HG
18  SILK ALMD_CCNT BLEND HG
19  SILK ALMOND 2CT HG
20  SILK ALMOND HG
21  SILK ALMOND LT HG
22  SILK CASHEW HG
23  SILK COCONUT HG
24  SILK QT ORGANIC
25  SILK SOY 2CT HG
26  SILK SOY HG
27  SILK SOY LT HG

是否有重命名我的变量并用带宏的名称替换数字(id)而不是手动?

示例:

  • a_17应重命名为a_SDDF_COCONUT_HG
  • a_18应重命名为a_SILK_ALMD_CCNT_BLEND_HG
  • ......等等

提前致谢并原谅我可怜的英语!

3 个答案:

答案 0 :(得分:2)

我的回答是假设您的所有变量都以' a _'开头。如果是这种情况,那么您可以使用查找数据集构建重命名语句,然后将其应用于proc datasets

/* required variable names */
data var_names;
input @1 id  @3 name $30.;
datalines;
17  SDDF COCONUT HG
18  SILK ALMD_CCNT BLEND HG
19  SILK ALMOND 2CT HG
20  SILK ALMOND HG
21  SILK ALMOND LT HG
22  SILK CASHEW HG
23  SILK COCONUT HG
24  SILK QT ORGANIC
25  SILK SOY 2CT HG
26  SILK SOY HG
27  SILK SOY LT HG
;
run;

/* build up rename statement, replacing spaces with underscores */
proc sql noprint;
select cats('a_',id,'=','a_',translate(trim(name),'_',' ')) 
        into :new_vars
        separated by ' '
from var_names;
quit;

%put &new_vars.;

/* cerate dummy dataset with vars a_17 - a_27 */
data have;
input a_17-a_27;
datalines;
1 2 3 4 5 6 7 8 9 10 11
;
run;

/* rename variables */
proc datasets lib=work nodetails nolist;
modify have;
rename &new_vars.;
quit;

答案 1 :(得分:1)

这是一个call execute解决方案:

/* required variable names */
data var_names;
input @1 id  @3 name $30.;  
datalines;
17  SDDF COCONUT HG
18  SILK ALMD_CCNT BLEND HG
19  SILK ALMOND 2CT HG
20  SILK ALMOND HG
21  SILK ALMOND LT HG
22  SILK CASHEW HG
23  SILK COCONUT HG
24  SILK QT ORGANIC
25  SILK SOY 2CT HG
26  SILK SOY HG
27  SILK SOY LT HG
;
run;

/* create dummy dataset with vars a_17 - a_27 */
data have;
array current_vars{*} a_17-a_27;
run;

data _null_;
    set var_names end = eof;
    if _n_ = 1 then     call execute('proc datasets lib= work; modify have; rename ');
                        call execute(cats('a_',id,'=','a_',tranwrd(trim(name),' ','_')));
    if eof then         call execute('; run; quit;');
run;

答案 2 :(得分:0)

下面的代码应该有所帮助。我创建了一个类似于你的数据集的数据集,它需要重命名cols和2nd" b"查找来自的值。

data a;
length a_17 a_18 a_19 8;
run;

data b;
input id  name $;
datalines;
17  SDDF
18  SILK
19  SILK21
;

proc sql noprint;
select id , name  into :id separated by ':', :name separated by ':' from b;
quit;

%put &id,&name;

%macro abc;

data a;
    set a;
    %let i =  1;
    %let id1 = %scan(&id,&i,":");

    %do %while( %str(&id1) ne );
        %let strng = a_%scan(&name,&i,":");
        rename a_&id1 = &strng;
        %let i =  &i+1;
        %let id1 = %scan(&id,&i,":");
    %end;
run;

%mend;

%abc;

HTH