2016-04-22 100 views
1

我是SAS新手,沒有找到我的問題的答案。也許這個社區會/可能如此善良來幫助我。宏變量的值作爲另一個變量的長度?

是否可以將宏變量的值定義爲另一個變量的長度?我知道宏的價值是個性,但是有一種方法可以做到嗎?

我的問題是這樣的:我想檢查我的變量最長的值,並設置最長值的長度作爲變量的新長度。所以我用這個程序:

proc sql; 

select max(length(variable)) 

into: length_variable 

from dm_comp; 
quit; 

%put length_variable; 

現在我的價值在我的微距人物,但我不知道如何使用這個宏設置一個新的長度。這樣做甚至有可能嗎?如果沒有,你有一個想法如何做得更好?非常感謝您的幫助。

回答

2

您可以使用數據步驟重新定義變量並從舊數據集中填充它。

/*Data with variable length 10, only need 2*/ 
data temp; 
length x $ 10; 
x="1"; 
output; 
x="11"; 
output; 
run; 

proc sql noprint; 
select max(length(x)) 
    into: length_variable 
from temp; 
quit; 

/*Puts 2 as expected*/ 
%put &length_variable; 

/*First define the variable and the new length, 
    Then "set" the Data step - rename the old variable. 
    Set the new variable to the old one (I strip whitespace here)*/ 
data temp(drop=x_old); 
length x $ &length_variable; 
set temp(rename=(x=x_old)); 
x = strip(x_old); 
run; 

/*CONTENTS Show us the new length*/ 
proc contents data=temp; 
run; 

結果

    Alphabetic List of Variables and Attributes 

         # Variable Type Len 

         1 x   Char  2 
+0

我不認爲你需要rename(x = x_old)部分或賦值語句。只需在SET語句之前添加一個長度語句即可。它會拋出一個關於截斷值的警告,你可以通過設置系統選項varlenchk = nowarn來避免這個警告。 – Quentin

+0

@Quentin,你是對的。我這樣做是爲了避免日誌中的警告,而無需更改系統選項。 – DomPazz

+0

非常感謝您的幫助。這工作。現在,如果我想將我的代碼放入宏中,如果我想重複使用它,該怎麼辦?
Kris

0

你在正確的軌道上。你只需要正確地格式化新變量:

proc sql; 
    select max(length(variable)) 
    into: length_variable 
    from dm_comp; 
quit; 

proc sql; 
    create table dm_comp2 as select 
     *, your_var as resized_var format %sysfunc(strip(&length_variable.)). 
     from dm_comp; 
quit; 
+0

更改格式與更改長度不同。該格式將影響值的顯示方式。長度影響它們的存儲方式。我想你會想'your_var resized_var length&length_variable' – Quentin