2013-09-25 55 views
-1

我有大約600個要動態重命名的變量。我使用PROC SQL來創建一個包含變量名稱的宏變量。現在他們看起來像:aayyy,abcjjjjj,bbcjjjjj等。我想在第一個2或3個字符(取決於變量)之後加下劃線,並保持其餘部分相同。所以最終的變量看起來像aa_yyy,abc_jjjjj,bbc_jjjjj。重命名SAS變量以添加下劃線

任何想法?

+0

需要更多信息在這裏。你能舉出你當前的代碼和一些示例數據的例子嗎? – Joe

+0

如果沒有明確/形式的確定是否插入「_」的模式,它將很難明確回答。無論哪種方式,我認爲你需要查看perl正則表達式(PRX)函數,因爲在這個階段,模式看起來很不規律。它們可以通過%SYSFUNC()宏函數在宏代碼中使用。您可以在每個單詞上循環使用PRX模式,並根據它是否匹配進行更改... – DJM

回答

3
libname anylib "E:\"; 
data anylib.table1; 
length aayyy eeeeee abcjjjjj bbcjjjjj abcdejd 8; 
run; 

data work.table2; 
length aayyy abcjjjjj bbcjjjjj abcdejd 8; 
run; 

proc sql; 
create table list as 
select * from (
select libname, memname, name, 
case 
when 
    compress(substr(name, 3), substr(name, 3, 1)) = '' 
    then catt(substr(name, 1, 2), '_', substr(name, 3)) 
when 
    compress(substr(name, 4), substr(name, 4, 1)) = '' 
    then catt(substr(name, 1, 3), '_', substr(name, 4)) 
else '' end 
    as newname 
from dictionary.columns 
where libname in ('WORK', 'ANYLIB') and length(name) >= 5 
and (substr(name, 3, 1) = substr(name, 4, 1) 
or substr(name, 4, 1) = substr(name, 5, 1) 
    ) 
) where newname is not null 
order by libname, memname 
; 
quit; 

data _null_; 
set list; 
length stmt $200; 
file "E:\renames.sas"; 
by libname memname; 
if first.libname then do; 
    stmt = 'proc datasets lib=' || libname || 'nolist nodetails;'; 
    put stmt; 
end; 
if first.memname then do; 
    stmt = 'modify ' || memname || ';'; 
    put stmt; 
    stmt = 'rename'; 
    put stmt; 
end; 
stmt = ' ' || name || ' = ' || newname; 
put stmt; 
if last.memname then do; 
    stmt = ';'; 
    put stmt; 
end; 
if last.libname then do; 
    stmt = 'quit;'; 
    put stmt; 
end; 
run; 

%include "E:\renames.sas"; 

背後compress(substr(的想法...是找到名字,其中第三或第四字符重複,直到名字的結束 - 壓縮消除了這個角色,併產生空字符串。 然後我們在數據步驟中生成腳本PROC DATASETS並運行(%include)它。