重命名包含撇号的非法变量

Renaming an illegal variable which contains an apostrophe

我是 SAS 的新手,我目前正在尝试创建一个宏,它将通过用下划线替换所有特殊字符的实例来重命名变量。我遇到了一个特定的问题,因为变量名称包含“'”,所以我收到一条错误消息。更明确地说,

Suppose we were to have a variable name "dumm'y?", under my macro, this should be renamed to "dumm_y_". The problem is that when I come to performing the renaming what SAS tries to compute is: rename 'dumm'y?'n = dumm_y_". The issue is the apostrophe in the variable name causes SAS to produce an error message.

我尝试使用 TRANSLATE(name, "_", "'") 将撇号替换为下划线,但这会导致错误,因为 SAS 将执行 RENAME 'dumm_y?'n = "dumm_y_',因为 dumm_y? 不是数据库中的变量名我正在尝试重命名。

我知道将 ' 的所有实例替换为 ",反之亦然,在 name = cats("'", name, "'n") 中将解决此问题。尽管如果变量名称是 dumm"y?.

问题仍然存在

N.B。我知道通过将 SAS 变量名称策略更改为 V7 将有效解决此问题。我有意创建这个宏来提高我的 SAS 技能。

/* Generate dummy data */
option validvarname = any;
data dummy_data;
    input "dumm'y?"n;
    datalines;
    1 
    2 
    3
    ;
run;


data badvarname (keep = name validname);
    set sashelp.vcolumn;
    where libname = "WORK" and memname = "DUMMY_DATA";
    
    validname = prxchange("s/[^a-zA-Z0-9]/_/", -1, trim(name));

/* Replacing the apostrophe with an underscore still causes an error */
/*      name = translate(name, "_", "'");  */
    name = cats("'", name, "'n"); 
run;


proc sql;
    select cats("rename", name, "=", validname, ";") into : renamelist
    separated by " " from badvarname;
quit;


data output_tab;
    set dummy_data;
    &renamelist.;
run;

使用 NLITERAL() 函数将元数据中的名称转换为可在 SAS 代码中使用的有效语法。不要在生成的宏变量中包含 RENAME 关键字。

proc sql noprint;
select catx('=',nliteral(name),nliteral(validname))
  into :renamelist separated by ' '
from badvarname;
quit;

...
  rename &renamelist ;
....

使用 NLITERAL 函数。

name = nliteral(name);