重命名变量而不管其在 SAS 中的名称 [英] Rename Variable Regardless of its Name in SAS

查看:85
本文介绍了重命名变量而不管其在 SAS 中的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下数据集:

Lets suppose we have the following dataset:

ID    Stress_Level    Heart_Rate
1          5              10
2          7              12
3          9              16

用来重命名变量的代码是:

And the code one would use to rename a variable would be:

data test1;
    set test0;
    rename Stress_Level=A Heart_Rate=B;
run;

但是,我想做的是重命名 2 列而不使用它们的名称.是否有内部"SAS 命令根据变量所在的列来寻址变量?因此,例如,作为第二列的 Stress_Level 可以被寻址为COL2"或类似的东西.因此代码将是:

However, what I would like to do is to rename the 2 columns without using their names. Is there an "internal" SAS command that addresses the variable depending on which column it is? So for instance Stress_Level which is the 2nd column could be addressed as "COL2 " or something similar. Thus the code would be:

data test1;
    set test0;
    rename COL2=A COL3=B;
run;

COL2"总是指数据集中的第二列,无论其名称如何.是否有直接或间接的方式来实现这一目标?

Where "COL2" would always refer to the second column in the dataset regardless of its name. Is there a direct or maybe an indirect way to achieve that?

推荐答案

我认为最简单的方法是从元数据表 DICTIONARY.COLUMNS(这个视图是 SASHELP.VCOLUMN)构建一个重命名语句字符串.这保存了活动库中所有表的列名和位置.
我利用了 ASCII 序列(byte 函数)来重命名列 A、B 等,显然如果表中要重命名的列超过 26 列,您会遇到问题!如果您想从与 2 不同的列开始,您还需要调整 varnum+63 计算.

I think the easiest way is to build up a rename statement string from the metadata table DICTIONARY.COLUMNS (the view of this is SASHELP.VCOLUMN). This holds the column names and position for all tables in active libraries.
I've taken advantage of the ASCII sequence (the byte function) to rename the columns A, B etc, obviously you'd run into problems if there are more than 26 columns to be renamed in the table! You'll also need to tweak the varnum+63 calculation if you wanted to start from a different column than 2.

proc sql noprint;
select cats(name,"=",byte(varnum+63)) into :newvars separated by ' '
from dictionary.columns
where libname = 'WORK' and memname='HAVE' and varnum>=2;
quit;

data want;
set have;
rename &newvars.;
run;

/* or */

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

这篇关于重命名变量而不管其在 SAS 中的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆