SAS - 函式



SAS 具有各種內建函式,有助於分析和處理資料。這些函式用作 DATA 語句的一部分。它們將資料變數作為引數,並返回儲存到另一個變數中的結果。根據函式的型別,它接受的引數數量可能會有所不同。有些函式接受零個引數,而其他函式接受固定數量的變數。以下是 SAS 提供的函式型別的列表。

語法

在 SAS 中使用函式的一般語法如下所示。

FUNCTIONNAME(argument1, argument2...argumentn)

此處,引數可以是常量、變數、表示式或其他函式。

函式類別

根據其用法,SAS 中的函式分類如下。

  • 數學函式
  • 日期和時間函式
  • 字元函式
  • 截斷函式
  • 其他函式

數學函式

這些函式用於對變數值應用一些數學計算。

示例

下面的 SAS 程式顯示了一些重要的數學函式的用法。

data Math_functions;

v1=21; v2=42; v3=13; v4=10; v5=29;

/* Get Maximum value */
max_val = MAX(v1,v2,v3,v4,v5);

/* Get Minimum value */
min_val = MIN (v1,v2,v3,v4,v5);

/* Get Median value */
med_val = MEDIAN (v1,v2,v3,v4,v5);

/* Get a random number */
rand_val = RANUNI(0);

/* Get Square root of sum of the values */
SR_val= SQRT(sum(v1,v2,v3,v4,v5));

proc print data = Math_functions noobs;
run;

執行上述程式碼後,我們將獲得以下輸出 -

math_funcs_result

日期和時間函式

這些函式用於處理日期和時間值。

示例

下面的 SAS 程式顯示了日期和時間函式的用法。

data date_functions;
INPUT @1 date1 date9. @11 date2 date9.;
format date1 date9.  date2 date9.;

/* Get the interval between the dates in years*/
Years_ = INTCK('YEAR',date1,date2);

/* Get the interval between the dates in months*/
months_ = INTCK('MONTH',date1,date2);

/* Get the week day from the date*/
weekday_ =  WEEKDAY(date1);

/* Get Today's date in SAS date format */
today_ = TODAY();

/* Get current time in SAS time format */
time_ = time();
DATALINES;
21OCT2000 16AUG1998
01MAR2009 11JUL2012
;
proc print data = date_functions noobs;
run;

執行上述程式碼後,我們將獲得以下輸出 -

date_time_funcs_result

字元函式

這些函式用於處理字元或文字值。

示例

下面的 SAS 程式顯示了字元函式的用法。

data character_functions;

/* Convert the string into lower case */
lowcse_ = LOWCASE('HELLO');
  
/* Convert the string into upper case */
upcase_ = UPCASE('hello');
  
/* Reverse the string */
reverse_ = REVERSE('Hello');
  
/* Return the nth word */
nth_letter_ = SCAN('Learn SAS Now',2);
run;

proc print data = character_functions noobs;
run;

執行上述程式碼後,我們將獲得以下輸出 -

char_funcs_result

截斷函式

這些函式用於截斷數值。

示例

下面的 SAS 程式顯示了截斷函式的用法。

data trunc_functions;

/* Nearest greatest integer */
ceil_ = CEIL(11.85);
  
/* Nearest greatest integer */
floor_ = FLOOR(11.85);
  
/* Integer portion of a number */
int_ = INT(32.41);
  
/* Round off to nearest value */
round_ = ROUND(5621.78);
run;

proc print data = trunc_functions noobs;
run;

執行上述程式碼後,我們將獲得以下輸出 -

trunc_funcs_result

其他函式

現在讓我們透過一些示例瞭解 SAS 的其他函式。

示例

下面的 SAS 程式顯示了其他函式的用法。

data misc_functions;

/* Nearest greatest integer */
state2=zipstate('01040');
 
/* Amortization calculation */
payment = mort(50000, . , .10/12,30*12);

proc print data = misc_functions noobs;
run;

執行上述程式碼後,我們將獲得以下輸出 -

Misc_funcs_result
廣告

© . All rights reserved.