2009-09-09 77 views
8

如果我有一個格式的數值變量,有沒有辦法將格式化的值作爲字符變量?如何使任意SAS格式的字符變量等於數值變量的格式化值?

例如我想寫下如下內容來將10/06/2009打印到屏幕上,但沒有putformatted()功能。

data test; 
    format i ddmmyy10.; 
    i = "10JUN2009"d; 
run; 

data _null_; 
    set test; 
    i_formatted = putformatted(i); /* How should I write this? */ 
    put i_formatted; 
run; 

(很明顯,我可以寫put(i, ddmmyy10.),但我的代碼需要爲任何格式i恰巧有工作)。

回答

9

VVALUE函數格式使用變量相關的格式傳遞給它的變量。下面是使用VVALUE代碼:

data test; 
    format i ddmmyy10.; 
    i = "10JUN2009"d; 
run; 

data _null_; 
    set test; 
    i_formatted = vvalue(i); 
    put i_formatted; 
run; 

雖然cmjohns解決方案是略快於這個代碼,這個代碼更簡單,因爲沒有涉及到宏。

+0

+1的當前格式進行格式化的方式:正是我之後所做的。謝謝! – 2010-01-15 22:16:13

3

我能做到這一點與宏代碼和sashelp.vcolumn,但它是一個有點繁瑣。

proc sql noprint; 
    select trim(left(format)) into :format 
    from sashelp.vcolumn 
    where libname eq 'WORK' and memname eq 'TEST'; 
run; 

data test2; 
    set test; 
    i_formatted = put(i, &format); 
    put i_formatted; 
run; 
+0

我喜歡通過cmjohns' – 2009-09-10 13:39:45

+0

@Chang Chung我知道這是一個古老的問題,但我被重定向到這裏。你有什麼理由比cmjohns的解決方案更喜歡這個嗎? @Simon同樣的問題給你:你爲什麼稱它有點煩躁?它不是100%穩定嗎? – Yoh 2011-05-04 18:57:17

+0

@Yohsoog:它的工作原理,它很穩定。我只是希望有一種方法可以做到這一點,而無需查看sashelp.vcolumn。 – 2011-05-05 08:28:06

5

這似乎適用於我試過的一對夫婦。我使用了VARFMT和一個宏函數來檢索給定變量的格式。

data test; 
    format i ddmmyy10. b comma12.; 
    i = "10JUN2009"d; 
    b = 123405321; 
run; 


%macro varlabel(variable) ; 
    %let dsid=%sysfunc(open(&SYSLAST.)) ; 
    %let varnum=%sysfunc(varnum(&dsid,&variable)) ; 
    %let fmt=%sysfunc(varfmt(&dsid,&varnum)); 
    %let dsid=%sysfunc(close(&dsid)) ; 
    &fmt 
%mend varlabel; 

data test2; 
    set test; 
    i_formatted = put(i, %varlabel(i)); 
    b_formatted = put(b, %varlabel(b)); 
    put i_formatted=; 
    put b_formatted=; 
run; 

這給了我:

i_formatted=10/06/2009 
b_formatted=123,405,321 
+0

+1,我接受這個答案,因爲它比putn(i,vformat(i))快得多。對於1000萬觀測值,這種方法需要10秒,而65秒。 – 2009-09-09 13:59:14

7

使用vformat()功能。

/* test data */ 
data test; 
    i = "10jun2009"d; 
    format i ddmmyy10.; 
run; 

/* print out the value using the associated format */ 
data _null_; 
    set test; 
    i_formatted = putn(i, vformat(i)); 
    put i_formatted=; 
run; 
/* on log 
i_formatted=10/06/2099 
*/ 
+0

+1我喜歡這個,並且在現在還不知道putn()或者vformat(),但是我因爲性能原因接受了cmjohns的回答。 – 2009-09-09 14:00:01

0

是的,有一個putformatted()函數。實際上,有兩個:putc()和putn()。 Putc處理字符格式,putn()數字。您的代碼需要查看格式名稱(所有字符格式和唯一字符格式均以「$」開頭)確定要使用哪種格式。這裏是putc將語法(從交互式的幫助):

PUTC(source, format.<,w>) 

參數

source 
is the SAS expression to which you want to apply the format. 

format. 
is an expression that contains the character format you want to apply to source. 

w 
specifies a width to apply to the format. 

Interaction: If you specify a width here, it overrides any width specification 
in the format. 
+0

但是我必須提供這樣的格式:問題的關鍵是要確定是否存在用變量 – 2010-01-14 22:17:04