2014年12月30日 星期二

R 環境設定相關語法

R 環境設定相關語法

以 windows 7 系統, R 3.1.2 為例子。


更改工具列的語系

  1. First, go to the "etc" folder under R program files folder.
  2. Then locate Rconsole file.
  3. Find the line "language = ", change it to "language = en" if you want to run R in English.
  4. Save the file.

例如:C:\Program Files\R\R-3.1.2\etc,裡頭的 Rconsole


更改系統時間為英文

先確認系統時間格式
Sys.getlocale("LC_TIME")
或者是
Sys.getlocale()

更改時間的顯示為 English
Sys.setlocale("LC_TIME", "English")

若全都要改為 enligh
Sys.setlocale("LC_ALL", "English")


顯示指令執行所花費的時間

利用 system.time() 這個指令,把要執行的指令放在( )中間,例如:

system.time(fread(file)) # 1.54 

system.time(read.table(file, header=TRUE, sep="\t"))  # 9.34

更新 r的版本,並所有package都會保留

  1. installing/loading the package:
    if(!require(installr)) { install.packages("installr"); require(installr)}

  2. using the package:
    updateR()

  3. 會接著檢查是否有新版本,接著提示語進行。

Source: installr-package


隱藏 print out 輸出到 console 裡

f1 <- function(x) x f2 <- function(x) invisible(x) f1(1) # prints f2(1) # does not


R MYSQL ,與 RMySQL package

環境 windows 7 64, R=3.1.2 64bit
必要軟體:
1. MYSQL server 5.6
2. Rtools
3. RMySQL package

步驟:
1. 安裝 MYSQL server 5.6,並找出安裝的目錄是在哪,例如:C:\Program Files\MySQL\MySQL Server 5.6\ ,步驟3會用到。
2. 安裝 Rtools,注意此頁的選項要勾

3. 設定 Renviron.site
在 C:\Program Files\R\R-3.1.2\etc\ 用 notepad 建立Renviron.site,並在該文件裡編輯輸入MYSQL_HOME=C:\Program Files\MySQL\MySQL Server 5.6\
4. 安裝RMySQL package
打開 R ,並執行install.packages('RMySQL',type='source')
應該會出現一大串訊息,其中會有一段類似以下
* installing *source* package 'RMySQL' ...
** package 'RMySQL' successfully unpacked and MD5 sums checked
** libs
rm -f RMySQL-init.o connection.o db-apply.o driver.o exception.o fields.o result.o utils.o
"C:/PROGRA~1/R/R-31~1.2/bin/x64/Rscript.exe" "../tools/winlibs.R"
** R
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded
* DONE (RMySQL)
5. 最後確認
在R 執行 Sys.getenv('MYSQL_HOME') 應該會出現
[1] "C:Program FilesMySQLMySQL Server 5.6"

Source: RMySQL

2014年12月24日 星期三

各種「理論」__網路搜集

1、蝴蝶效應:上個世紀70年代,美國一個名叫洛倫茲的氣象學家在解釋空氣系統理論時說,亞馬遜雨林一隻蝴蝶翅膀偶爾振動,也許兩周後就會引起美國德克薩斯州的一場龍捲風。
蝴蝶效應是說,初始條件十分微小的變化經過不斷放大,對其未來狀態會造成極其巨大的差別。有些小事可以糊塗,有些小事如經系統放大,則對一個組織、一個國家來說是很重要的,就不能糊塗。

2、青蛙現象:把一隻青蛙直接放進熱水鍋裡,由於它對不良環境的反應十分敏感,就會迅速跳出鍋外。如果把一個青蛙放進冷水鍋裡,慢慢地加溫,青蛙並不會立即跳出鍋外,水溫逐漸提高的最終結局是青蛙被煮死了,因為等水溫高到青蛙無法忍受時,它已經來不及、或者說是沒有能力跳出鍋外了。
青蛙現象告訴我們,一些突變事件,往往容易引起人們的警覺,而易致人於死地的卻是在自我感覺良好的情況下,對實際情況的逐漸惡化,沒有清醒的察覺。

3、鱷魚法則:其原意是假定一隻鱷魚咬住你的腳,如果你用手去試圖掙脫你的腳,鱷魚便會同時咬住你的腳與手。你愈掙扎,就被咬住得越多。所以,萬一鱷魚咬住你的腳,你唯一的辦法就是犧牲一隻腳。
譬如在股市中,鱷魚法則就是:當你發現自己的交易背離了市場的方向,必須立即止損,不得有任何延誤,不得存有任何僥倖。

4、鯰魚效應:以前,沙丁魚在運輸過程中成活率很低。後有人發現,若在沙丁魚中放一條鯰魚,情況卻有所改觀,成活率會大大提高。這是何故呢?原來鯰魚在到了一個陌生的環境後,就會「性情急躁」,四處亂遊,這對於大量好靜的沙丁魚來說,無疑起到了攪拌作用;而沙丁魚發現多了這樣一個「異已分子」,自然也很緊張,加速遊動。這樣沙丁魚缺氧的問題就迎刃而解了,沙丁魚也就不會死了。

5、羊群效應:領頭羊往哪裡走,後面的羊就跟著往哪裡走。
羊群效應最早是股票投資中的一個術語,主要是指投資者在交易過程中存在學習與模仿現象,「有樣學樣」,盲目效仿別人,從而導致他們在某段時期內買賣相同的股票。

6、刺蝟法則:兩隻睏倦的刺蝟,由於寒冷而擁在一起。可因為各自身上都長著刺,於是它們離開了一段距離,但又冷得受不了,於是湊到一起。幾經折騰,兩隻刺蝟終於找到一個合適的距離:既能互相獲得對方的溫暖而又不至於被紮。
刺蝟法則主要是指人際交往中的「心理距離效應」。

7、手錶定律:手錶定律是指一個人有一隻表時,可以知道現在是幾點鐘,而當他同時擁有兩隻時卻無法確定。兩隻表並不能告訴一個人更準確的時間,反而會使看錶的人失去對準確時間的信心。
手錶定律在企業管理方面給我們一種非常直觀的啟發,就是對同一個人或同一個組織不能同時採用兩種不同的方法,不能同時設置兩個不同的目標,甚至每一個人不能由兩個人來同時指揮,否則將使這個企業或者個人無所適從。

8、破窗理論:一個房子如果窗戶破了,沒有人去修補,隔不久,其它的窗戶也會莫名其妙地被人打破;一面牆,如果出現一些塗鴉沒有被清洗掉,很快的,牆上就佈滿了亂七八糟、不堪入目的東西;一個很乾淨的地方,人們不好意思丟垃圾,但是一旦地上有垃圾出現之後,人就會毫不猶疑地拋,絲毫不覺羞愧。

9、二八定律(巴萊多定律):19世紀末20世紀初義大利的經濟學家巴萊多認為,在任何一組東西中,最重要的只佔其中一小部分,約20%,其餘80%儘管是多數,卻是次要的。社會約80%的財富集中在20%的人手裡,而80%的人只擁有20%的社會財富。這種統計的不平衡性在社會、經濟及生活中無處不在,這就是二八法則。
二八法則告訴我們,不要平均地分析、處理和看待問題,企業經營和管理中要抓住關鍵的少數;要找出那些能給企業帶來80%利潤、總量卻僅佔20%的關鍵客戶,加強服務,達到事半功倍的效果;企業領導人要對工作認真分類分析,要把主要精力花在解決主要問題、抓主要項目上。

10、木桶理論:組成木桶的木板如果長短不齊,那麼木桶的盛水量不是取決於最長的那一塊木板,而是取決於最短的那一塊木板。

2014年8月13日 星期三

在字串中找出 substring的位置

 /*
INDEX     (source,  excerpt  )  與條件完全相符的字串去找
FIND        (string,substring<,modifiers> <,startpos> )   與條件完全相符的字串去找,可設'I'忽略大小寫、'T'皆trim,搜尋的起點

INDEXC  (source,  excerpt-1 <,… excerpt-n> ) 以條件內的任一個字母、數字或符號去找
INDEXW (source, excerpt      <,delimiters>   )  以完全相符的單字組去找,預設分隔是space
*/


data test_index;
   a = 'ABC.DEF (X=Y)';
   b = 'X=Y';
  x_ab = index(a,b);     put x_ab= ;
  f_ab_1=find(a,b);      put f_ab_1=;
  f_ab_2=find(a,b,11);      put f_ab_2=; *超過了;
  f_ab_3=find(a,'a',  'I');      put f_ab_3=; *Ignore 大小寫;

length bt $10. ;
bt='X=Y';
  x_abt_1 = index(a, bt);     put x_abt_1= ;*bt尾要補至12位元的空白;
  x_abt_2 = index(a, trim(bt) );     put x_abt_2= ;
  F_abt_1 = find(a, bt, 'T' );     put f_abt_1= ; *兩者皆Trim;
 
c='X=Y=F' ;
  xc_ab_1 = indexc(a, c                       );     put xc_ab_1= ; *找到F;
  xc_ab_2 = indexc(a, c,  'abc.( )'       );     put xc_ab_2= ;

  wc_ab_1 = indexw(a, 'DEF'               );     put wc_ab_1= ;
  wc_ab_2 = indexw(a, 'DEF' ,    '.'      );     put wc_ab_2= ; *尾端有空白;
  wc_ab_3 = indexw(a, 'DEF' ,    '. '      );     put wc_ab_3= ;*逗點接空白;
run;

2014年8月6日 星期三

Delete等於的records,就是保留不等於的records??

希望留下 Sex 和 disnn2 都不為 Missing的部分,但因為在「趕時間」,再轉換IF-then-else 與 SET 裡的 where 時,很直覺地把,IF-then-else 裡的 Delete「等於的」records,改為SET 裡的 Where 保留「不等於」的records
真能如此嗎?

有一組資料如下

Sex disnn2 i
. . 1
. 0 2
. 1 3
1 . 1
1 0 2
1 1 3
2 . 1
2 0 2
2 1 3
目標:留下 Sex 和 disnn2 都不為 Missing的部分
轉譯:
1. Sex 或 disnn2 有Missing 就該刪
【直接轉換 Missing—>不是Missing,刪—>留】
2. Sex不是Missing 或 Disnn2不是Missing就要留
方法
結果
data t1 ; set n_copy;
if sex=. or disnn2 =. 
                  then delete ;
put sex disnn2;
run;
1 0
1 1
2 0
2 1
data test1 ; set n_copy;
if sex^=. or disnn2 ^=.  ;
put sex disnn2;
run;
. 0
. 1
1 .
1 0
1 1
2 .
2 0
2 1
正確的應該再多一道手續,OR 轉為 AND
方法
結果
data t2 ; set n_copy;
if sex^=. and disnn2 ^=.  ;
put sex disnn2;
run;
1 0
1 1
2 0
2 1

2014年7月17日 星期四

以Batch 模式執行SAS的簡便語法


=====================================================
:SAS Batch 檔輸出,這裡可寫說明
:以下設定參數代表的意義
set src=C:\
set code=test_pgm.sas
set log=C:\
set prt=C:\
:以下為呼叫SAS的指令
"C:\Program Files\SASHome\x86\SASFoundation\9.3\sas.exe" -nologo -nosplash -sysin "%src%%code%" -print "%prt%" -log "%log%"
exit
=====================================================

注意事項:

  1. 要使用,請將上面線內的語法貼到notepad裡,並將副檔名存成 batch。
  2. set的部分,src,log,prt分別是在設定sas語法、log、output存放的路徑,而 code則在指定sas語法檔名
  3. 最後一段SAS指令的部分為完整的一列,就是在同一列裡,中間並沒有用Enter換行。而 -sysin 之後立馬要接sas語法檔的詳細路徑。-print 與 -log 若不指定路徑,預設會出現在含有 sas.exe 的資料匣裡。




參考來源:
http://forum.slime.com.tw/thread136868.html
https://communities.sas.com/message/107052

2014年7月10日 星期四

常用的資料整理程式

/*依 ID,Merge 兩個資料檔 ,再依某變項 (cmdecod),保留唯一的值*/

/*方法一*/
DATA t ; merge cm(in=a )  treat ; by subjid  ;  if a ;
run;
proc sort data=T    nodupkey out=t3;
by subjid cmdecod;
run;

/*方法二*/
DATA t ; merge cm(in=a )  treat ; by subjid  ;  if a ;
run;
data t2  ; set t ; by subjid cmdecod;
if first.cmdecod;
run;

/*方法三*/
proc sql
   noprint;
   create table cmtosum as
      select unique (c.cmdecod) as cmdecod, c.subjid, t.trtcd
         from cm as c, treat as t
         where c.subjid = t.subjid
         order by subjid, cmdecod;
quit;


/*依組別(藥名),把資料檔由直向拉成橫向*/

/*方法一*/
Proc sort    data = counts;       by cmdecod trtcd; run;
Data cc2 ; set counts; by cmdecod trtcd;
/*記住3個變項值,不然數據長成一斜線*/
Retain n1-n3;
/*新組別時,先清空數據*/
Array nn {3} n1-n3;
   if first.cmdecod then do i =1 to 3;
nn{i}=.;
   end;
/*指定數值,亦可用Array的方式 nn{trtcd} ,但本例 trtcd有missing,固改用 if then 的方式*/
  if trtcd=. then n1=frequency;
  if trtcd=0 then n2=frequency;
  if trtcd=1 then n3=frequency;
/*輸出每組的最後一筆*/
if last.cmdecod;
run;

/*方法二*/
Proc sort    data = counts;  by cmdecod trtcd; run;
/*利用 Merge ,分組別進行*/
Data cm;
   merge counts(where = (trtcd = 1) rename = (frequency = count1))
         counts(where = (trtcd = 0) rename = (frequency = count2))
         counts(where = (trtcd = .) rename = (frequency = count3))
         end = eof;
      by cmdecod;
run;

/*方法三*/
/*較不建議,若是 ID 的變項值為 missing ,資料會被刪除*/
Proc transpose data=counts prefix=nn out=cc ;
by cmdecod ; id trtcd;
var Frequency;
run;




部分程式引用,Ref:  Jack Shostak, SAS Programming in the Pharmaceutical Industry.

2014年7月9日 星期三

常用的Macro

/*資料筆數存成 Macro Variable*/
/*方法一*/
Proc Sql noprint;
/*Macro Variable N1 */
select Count ( Distinct subjid ) format=3.
into :N1
      from treat
      where trtcd = 1;

 /*Macro Variable N2 */
select count(distinct subjid) format = 3.
      into :n2
      from treat
      where trtcd = 0;
Quit;
%put &N1 &N2;

/*方法二*/
data _null_;
   set treat end = eof;
   **** 分組的 COUNTER 並 retain 住;
   if trtcd = 1 then
      n1 + 1;
   else if trtcd = 0 then
      n2 + 1;
   **** 總 COUNTER.;
   n3 + 1;
   **** 資料最後一列即為所要的數值;
   if eof then
      do;  
         call symput("n1", put(n1,3.)); *用 PUT 數值轉為文字;
         call symput("n2", put(n2,3.));
         call symput("n3", put(n3,3.));
      end;
run;


/*一組變項定義為 Macro Variables*/
/*方法一 用 Arrary*/
DATA A;
Array Vars {8} $18.     (
'Dis_hypertension'
'Dis_DM'
'Dis_hyperlipidemia'
'Dis_stroke'
'dis_asthma'
'Dis_Kidney'
'Dis_HD'
'Dis_osteoporosis'
)  ;
Do i =1 to 8;
Call symput (  'I_num'  , compress(i)  );
Call symput (  'Vv'||compress(i) , Vars{i}  );
End;
run;
%Put   &I_num;
%Put &Vv1 &Vv2  &Vv8 ;

/*方法二 用資料檔處理的方式*/
%LET Text=  那一整群變項;
/*以變項群建立新資料檔(橫向)*/
DATA M_LIST ; input &text;   run;
/*讀 sashelp.Vcolumn取得資料檔訊息(直向)*/
Proc Sql;
Create Table M_LIST2  AS Select Name as MVAR_LIST   From sashelp.Vcolumn
Where libname='WORK' and memname='M_LIST' ;
Quit;
/*以及變項群數目*/
Proc Sql noprint;
Select nvar into :Num  From Sashelp.Vtable
Having libname='WORK' and memname='M_LIST' ;
Quit;
/*巨集變項名稱 Var1,  Var2, ~ VarN */
DATA M_Vars  (Keep= MVAR_PRE);
Pre='Var' ;
do i=1 to &Num;   MVAR_PRE=Pre||compress(i);  output;  End;
run;
/*Macro name 與 變項群 MERGE,Symput為 Macro Variable*/
DATA _NULL_  ; Merge M_vars M_list2 ;   Call Symput ( MVAR_PRE, MVAR_LIST);  run;

2014年6月30日 星期一

十大死因排名、死亡人數

Chronic diseases dominate death stats: MHW

Thursday, June 26, 2014
By Joy Lee, The China Post 

TAIPEI, Taiwan -- The Ministry of Health and Welfare (MHW) yesterday announced the latest cause of death statistics, and chronic diseases take up seven spots on the top-10 list for 2013.
According to the MHW, since the aging of the population in Taiwan has intensified, more people than ever before are dying from chronic diseases.

The MHW said that out of every 100 people, 64 die from chronic diseases like diabetes or hypertension.

According to the MHW, the average time between deaths, the annual number of people who died from cancer and the difference between the average lifespan of both sexes all reached record highs in 2013.

The total number of deaths recorded last year was 154,374, translating into one death every 3 minutes and 24 seconds; the average death rate in 2012 was one per every 3 minutes and 25 seconds.

The MHW said that cancer has been the number one cause of death for 32 years straight, and a total of 44,791 died from cancers, which suggests that one cancer patient passed away every 11 minutes and 44 seconds.

The 10 leading causes of death in 2013 were cancer, heart disease, cerebrovascular disease, diabetes, pneumonia, accidents, lower respiratory illness, hypertensive disease, chronic liver disease and nephrotic syndrome and nephritis.

Compared to the 10 leading causes of death 10 years ago, the MHW said, the rankings for heart disease, pneumonia and hypertensive disease soared dramatically while the rankings for nephrotic syndrome and nephritis and chronic liver disease dropped as a result of new advanced medical treatments for those diseases.

To further analyze common causes of death, the MHW said that the main cause of death for children under the age of 14 is cancer; the main cause for people between the ages of 15 and 24 is accident; and for people over the age of 25, the main cause of death is cancer.

In general, according to the MHW, about 64.2 percent of people who died last year died from the seven chronic diseases that are included in the 10 leading causes of death.

Wu Chien-yuan, division chief of the Bureau of National Health Promotion's Cancer Control and Prevention Division, said that nearly 70 percent of people who passed away last year were people over 65 years old.


Wu said that compared to young people, elders have a higher likelihood of suffering from cancers, which means that as people age, their risk of cancer increases.
====================================================================

年齡說法
people under the age of 14
people between the age of 15 to 24
people over the age of 25
people over 25 years old

14-year-old individual

職稱講法
Prof. Peter Wang, Deputy Director, National Taiwan University
Peter Wang, division chief of the Bureau of Health Promotion's Cancer Control and Prevention Division

數字說法
23,569,741,168  
twenty-three billion, five hundred and sixty-nine million, seven hundred and forty-one thousand, one hundred and sixty-eight

154,374
one hundred and fifty-four thousand, three hundred and seventy-four

220,000,000
Two hundred and twenty million

2014年4月28日 星期一

運用 Do loop 整理資料

  • /*
    DO index-variable=start TO stop BY increment;
    SAS statements
    END;
    */
    • data test;
      Amount=1000;
      Rate=.075/12;
      do month=1 to 12; /*開始 Iteration */
          Earned+(amount+earned)*rate;
      end;  /*month 跑到 13 才停,因此最後是 13 */
      run;  /*輸出 所有變項值*/
    • do i=1 to Years;
      變項也可以當成 Stop 的依據
    • /*Decrementing DO Loops ,最後到 1 結束*/
    • a Series of Items
      • DO index-variable=
        2,5,9,13,27;
      • DO index-variable=
        'MON','TUE','WED','THR','FRI';
      • DO index-variable=
        Spring, Summer, Fall , Winter;  變項值

/*Nesting DO Loops*/
  • data work.earn;
    do year=1 to 20; /*每年增資*/
        Capital+2000;
        do month=1 to 12; /*每月複利*/
            Interest=capital*(.012/12);
            capital+interest;
        end;
    end;
    run;

/*Conditionally Executing DO Loops*/
  • /* DO UNTIL(expression); */
    在程式底才判斷,因此statement一定至少執行一次
    • data invest;
          do until (Capital>=9000);
              capital+1000;
              capital+capital*.10;
              Year+1;
              output;
          end;
      run;
      proc print noobs;run;
    • data invest;
          do Year=1 to 10  until (Capital>=20000);
              capital+1000;
              capital+capital*.10;
              output;
          end;
      if year=11 then year=10;
      /*index-variable 跑足就會多 1  */
      run;
      proc print noobs;run;
    • data invest;         /*依 condition 提早結束*/
          do Year=1 to 10  until (Capital>=20000);
              capital+5000;
              capital+capital*.10;
              output;
          end;
          if year=11 then year=10;
      run;
      proc print noobs;run;
  • /* DO WHILE(expression); */
    在程式初就判斷,因此statement可能完全不執行
    • data invest;
          do while (Capital>=9000);
      *不會執行,因為初始是 0 ,要 >= 9000 才會動;
              capital+1000;
              capital+capital*.10;
              Year+1;
              output;
          end;
      run;

系統抽樣 搭配 Point-Output-Stop
  • DATA TT;
        Do sample=1 to 206 by 5 ;
            SET SASUSER.frequentflyers  point=sample;
            Output;
        End;
                    Stop;
    RUN;

2014年4月27日 星期日

建構變項—SAS Funtion

function-name(argument-1<,argument-n>);

  • mean(x1,x2,x3)
  • mean(of x1-x3)
    • mean(x1-x3)變成 x1-x3 的平均
  • mean(of narray{*})

 

文字與數值之間轉換

  • 多數的function使用時,系統可自行轉換,建立一個暫時變項,但遇到 $ , 等情況會失效
  • Input 可 Character-to-Numeric Conversion
    • INPUT(source, informat)
      New=Input ( ID ,  4. )
  • Put 可 Numeric-to-Character Conversion
    • PUT (source,format)
      • Fee_lv2=put( fee, 3.);
      • Fee_lv2=put( fee, fee.);
      • Fee_lv=input(  put( fee, fee.),  $10. );

========================
與 Date Value 有關的 function
========================

  • now1=mdy(4,27,2014); format now1 date9.;
    now2='27Apr2014'd;    format now2 date9.;
  • now3=today(); format now3 mmddyy10.;
    now4=date(); format now4 mmddyy8.;
  • nowtime=time(); format nowtime TIME8.;
    nowtime2='27Apr2014:15:35:00'dt; 
    format nowtime2 datetime.;

now1=
mdy(4,27,2014);

不正確的用法
mdy(Apr,27,2014);
mdy(‘Apr’,27,2014);

format now1 date9.;

27APR2014

now2=
'27Apr2014'd;

format now2 date7.;

27APR14

now3=today();




now4=date();

format now3 mmddyy10.;

format now4 mmddyy8.;

04/27/2014

04/27/14

nowtime=time();

format nowtime TIME8.;

15:35:17

nowtime2=
'27Apr2014:15:35:00'dt;

format nowtime2 datetime.;

27APR14:15:35:00

 

  • day=day(now1); /*27APR2014*/
    27
    month=month(now1);
    4
    year=year(now1);
    2014
  • qtr=qtr(now1);
    2
  • weekday=weekday(now1);
    1 /*日一二三四五六*/

 

  • 時間間隔
    INTCK('interval',from,to) 
    INTCK ( 'day' , '31dec2013'd , '01jan2014'd );
    常用於算周年
    • Day  經過幾個日數----------  1日
    • Week 經過幾個Sunday ----- 0個 Sunday
      • from為周日,to為周一,則0個Sunday
      • from為周六,to為周日,則1個Sunday
    • Month 經過幾個某月1日------1個某月1日
    • Year 經過幾個1月1日---------1個1月1日
      • Years = intck ( ‘year’, First_meet, Today() );

 

    • 時間推移
      INTNX('interval',startfrom,
                             increment<,'alignment'>)
      'alignment' 可為 b m e s,用於 month較易懂,其他interval 的不是很懂
      • Month
        • MonthX=intnx ('month','27apr2014'd, 5 , 'alignment' );
          推 5個月,b m e s的結果依序為
          01SEP2014月初
          15SEP2014月中
          30SEP2014月尾
          27SEP2014同日

 

日期之差

  • DATDIF(start_date,end_date,basis)
    • basis 有
      '30/360'   'ACT/ACT' 
  • YRDIF(start_date,end_date,basis)
    • basis 有
      '30/360'   'ACT/ACT'   'ACT/360'   'ACT/365'

 

=========================
與 文字 有關的 function
========================

傳出變項裡的字串,或者取代字串

  • SCAN(argument,n<,delimiters>)
    • 依 delimiter 區分,來選字第n個字,leading delimiters have no effect,預設的delimiter 有
      blank . < ( + | & ! $ * ) ; ^ - / , %
    • SCAN產生的新變項預設為 $200. 
      最好先設定 LENGTH
    • 新變項=scan (Name , 2,  ' -'  );
      delimiter 是 空白 與 -
    • 新變項=scan (Name , 2,  '-'  );
      delimiter 只有 -  
  • SUBSTR (argument, position <,n>)
    n表示連著取n個字元,不指定 n 就是position之後全要了。數值變項,請先Put成文字變項。
    • 依 position 來選字
      • First=Substr ( name , 1, 5) ;
    • 依 position 來取代文字,類似 TRANWRD
      • Substr ( name , 1, 5  ) ='First';
      • 有意義一點的作法是
        IF Substr ( name , 1, 1  ) = 'M'
             then Substr ( name , 1, 2  ) ='W%';
        注意新增的文字的 n 要對,本例為2個字元。
  • TRANWRD(source,target,replacement)
    搜查特定文字,並取代該文字。記得設定 length
    • Nname=TRANWRD ( name , 'M' ,  'W%' );

 

刪除多餘空白

  • TRIM(argument)
    刪除trailing blanks,用於組合文字
    新變項的length有可能多於實際文字量,因此還是會有trailing blanks
    • new=trim(Lastname) || ', ' || trim(location) || ', ' || trim(phone) ;
  • CATX(separator,string-1 <,...string-n>)
    • 用於連結字串,移除 leading and trailing blanks, 插入分隔符號( separator)。
      相當於TRIM and LEFT 的組合
    • new2=catx ( ', ' , Lastname, location, phone);

 

找字串的Position

  • INDEX(source,excerpt)
    搜尋特定字串(case sensitive),並回傳找到第一個的位置,若找無就是0
    • n1=INDEX (Lastname,'LA') ;
  • FIND(string,substring<,modifiers><,startpos> )
    用途與INDEX相近
    • n2=Find (Lastname,'LA') ;

 

大小寫文字的轉換

    • UPCASE(argument) 全大寫
    • LOWCASE(argument) 全小寫
    • PROPCASE(argument<,delimiter(s)>) 依分隔點區分,首字元大寫

 

========================
與 數字 有關的 function
========================

INT(argument) 取整數部分

ROUND(argument,round-off-unit) 類似四捨五入

  • d1 = round(1234.56789,100)     - 1200;
    d2 = round(1234.56789,10)      - 1230;
    d3 = round(1234.56789,1)       - 1235;
    d4 = round(1234.56789,.1)      - 1234.6;
    d5 = round(1234.56789,.01)     - 1234.57;
    d6 = round(1234.56789,.001)    - 1234.568; 
    d7 = round(1234.56789,.0001)   - 1234.5679;
    d8 = round(1234.56789,.00001)  - 1234.56789;

2014年4月26日 星期六

結合SAS Data Set

結合SAS Data Set
  • One-to-one merging (應該改很少用 @@)
    • 新資料檔有所有的變項,兩資料檔的數據依序進入 PDV,因此相同變項時,第1資料檔會被覆寫,保留第 2資料檔的數據。
    • Observation 只留「最少」資料檔的筆數。PDV 會進第1資料檔的第3筆,但是讀第2資料檔時會遇到 end-of-file,PDV就停止進資料,也不會輸出到新檔案中。
    • 用 Set
    • Data ab ;
      set a ;
      set b ;

      run;
      • Data-set-A 
        Num    X
        1          10
        2          15
        3          20
      • Data-set-B 
        Num       Y
        11           6
        13          12
      • Combined Data-set
        Num    X        Y
        11       10        6
        13       15       12
    • Data ab ; Merge a b; 則是會保留「最多」的Observation。
  • Concatenating 垂直連接,成為新資料檔
    • 新資料檔有所有的變項,也有所有的 Observation
    • 同變項,要有相同的 attribute,若是 type 不同( NUM 與 Char) 會有 Error;若是同屬性,但length, Label, format, informat 不同,會以先讀入的為主。
    • 用 SET 
    • Data ab ;
      set  a  b;
      run;
      • Data-set-A 
        Num    X
        1          10
        2          15
        3          20
      • Data-set-B 
        Num    Y
        11           6
        13          12
      • Combined Data-set
        Num    X        Y
        1          10        .
        2          15        .
        3          20        .
        11            .         6
        13            .        12
  • Appending 附加,以原來 BASE為主,加在尾部
    • PROC APPEND                            
                 BASE=Base-data-set          DATA=Second-data-set  FORCE;
      RUN;
    • 將 Second-data-set 的數據是加在 Master( Base) data-set 的尾部,沒有產生新 data-set,也不去讀取  Master( Base) data-set。
    • 一次 Procedure 只能處理 2 個資料檔,Base 與 Second。
    • 若 Second-data-set  的變項 有下列情況,要用 FORCE option;
      • 有新的變項,不在 Base-data-set 裡
        • Base沒有的變項會被 drop。
      • 同名變項 的 type 不同, length 不同。
        • 維持 Base 的type, Second-data-set的數據變missing;
          維持 Base 的Length,Second-data-set的數據被刪截;
  • Interleaving 插入數據 ( Concatenating 加入 BY )
    • 所有資料必須先 Sort in Ascending order.
    • Set, By
      Data ab ; set a b ; by num; run;
      • Data-set-A
        Num     X
        1          10
        2          15
        3          20
      • Data-set-B
        Num     X   Y
        1           6    6
        3          12   12
      • Combined Data-set
        Num     X    Y
        1          10     .
        1            6     6
        2          15     .
        3          20     .
        3          12    12
  • Match-merging
    • MERGE, BY
      • 最好都先排序成 Ascending order,By值是missing排在頂,Execution Phase: PDV會依照BY值序順進行比對。
      • 變項屬性以第 1個資料檔為主,但變項值則會被後到的資料 overwritten。
      • 變項改名字
        • Data-set ( RENAME= ( old-variable-name=new-variable-name ) ) 
    • Excluding Unmatched Observations
      • (IN= data set option) 與 If statement,產生 temp_a, temp_b 兩個 temporary variable,再利用 If statement 進行篩選所要輸出的資料檔
        • 全部資料都留
          Data Mab ;
          merge  a ( in= temp_a)   b ( in=temp_b  rename=(x=new_x) );
          by Num;
          If     temp_a or temp_b  ;    *或者不寫 If statement;
          run;
        • 只留完全 match ,AB兩資料檔都有的,把 if 段改如下
          If     temp_a and  temp_b  ;
          或者
          If     temp_a =1 and  temp_b  =1 ;
        • 保留只在 A  或是 只在 B的
          If     temp_a ;
          If     temp_b  ;

2014年4月25日 星期五

SAS 資料處理技巧1

變項Keep 與 Drop
  • data work (drop=age group);
  • set clinic    (keep=age group BMI );
    • 讀檔時 (SET) 只進 age group BMI ,新資檔(DATA) 刪除 age group,最後輸出只有BMI


FIRST.變項 與 LAST.變項
  • 一定要先Proc Sort
  • Proc Sort 之後,遇到 Data ; by X Y;,在program data vector裡會自動建立FIRST.變項 與 LAST.變項,First.X Last.X First.Y Last.Y,可參考下表
Department FIRST.Department LAST.Department
A 1 0
A 0 0
A 0 1
B 1 0
B 0 1
C 1 1

範例如下:
data salaries2 ; set salaries ;
by Department;
/*第一筆設定為0*/ 
if first.Department then Payroll=0;
/*累加*/
      payroll+yearly;
/*是最後一筆再輸出*/
if last.Department;
run;

Using Direct Access:指定讀特定一筆數據,並輸出。(Point-Output-Stop)
  • Point 與 OUTPUT 聯用。通常用於取得Random sample。
    • data test;
          obsnum=3; /*自定變項與值*/
          set salaries  point=obsnum;  /* 被 point 變項就消失 */
          N=1;
          OUTPUT;  /*強制輸出到實體資料檔*/
          Stop;     /*找到某筆數據後,停止 iteration,不
                          必等到 Mark of the end */
      K=1;   /*因為在OUTPUT之後,數值不會被輸出*/
      run;

資料列末端的技巧 ( End=var )
  • 用途:輸出資料檔的最未一筆總計。(似乎用Last.即可)
  • End=var,建立暫時變項 var ,若 SET statemnet 讀到了 end of file,var就為1
  • END= 不與 POINT= 一起用
    • set sasuser.stress2(keep=timemin timesec) end=last;
    • .........
    • if last; /* 當 last = 1 才輸出 */

SAS DATA SET 的處理流程,與讀 Raw data file 差不多,主要差異如下:
  • Execution Phase:第一筆資料輸出到新資料檔後,會在 Program Data Vector裡 Retain 保留 SET statement 已讀入的 (如:第一筆資料) 與 sum statement 所產生的變項,一直到再執行 SET statement,讀入第二筆數據
    • 但讀 RAW DATA FILE 則是重設為 MISSING,除非是RETAIN, SUM STATEMENT變項, 暫時的ARRARY,FILE或INFILE的OPTION建立的變項,自動變項

2014年4月24日 星期四

建構變項

累積加總
  • data stress; set sasuser.stress2;
    TotalTime=(timemin*60)+timesec;
    SumSec+totaltime;
    run;
    • SumSec 在 + 的左邊,它的起啟值就是 0 ,而非 missing
    • 其結果類似以下右欄
      1  1
      1  2
      1  3
      1  4

RETAIN variable <initial;-value>;
  • 主要特色
    • data complie 的指令,無法作用於 set, merge的變項
    • 指定變項初始值為任何文字或數字,避免變項在每次iteration被重置
  • SumSec 由10000 起算而非 0
    retain SumSec 10000;
    sumsec+totaltime;

IF-THEN/ELSE 的指令,會比 很多的 IF-THEN 更省資源,或者改用 SELECT-WHEN 的語法
  • SELECT (select-expression);
    WHEN ( condition,…, condition ) Execute-statement;
    WHEN ( condition,…, condition ) Execute-statement;
    OTHERWISE <Execute-statement>;
    END;
    • select (TimeMin) ;
          when ( '13' ) TimeGroup='Lower';
      雖然TimeMine是數值,也一定要 “”
    • OTHERWISE  一要有,否則有
      ERROR: Unsatisfied WHEN clause


變項特性的設定
  • The length of a new variable is determined by the first reference in the DATA step。若要用LENGTH 來指定變項長度,應放在最前端的程式。
    • length Test $ 10;
  • LABEL var= ‘Description’;
  • FORMAT var formats;

DROP and KEEP 變項
  • 用在 Data 、set 、Proc data= 的 Option
    • (DROP=variable(s))
      (KEEP=variable(s))
      • data work (drop=age group);
      • set clinic    (keep=age group BMI );
      • 讀檔時 (SET) 只進 age group BMI ,新資檔(DATA) 刪除 age group,最後輸出只有BMI
  • 在 DATA step 的statement
    • DROP variable(s) ;
      KEEP variable(s);

2014年4月23日 星期三

準備Base programming 筆記_HTML Output

ODS 有很多 Destinations,其中常用的是 LISTING, HTML, OUTPUT, PDF 等。

輸出 ODS HTML
  1. ODS HTML BODY="file-specification"   STYLE=style-name;               
                    /* BODY 可用 FILE*/
  2. ODS HTML BODY=fileref;  * 特定檔案才可;
  3. ODS HTML PATH=mine.mycat BODY=name.HTML;
    • procedure 1 ~ procedure N
  • ODS HTML CLOSE;


多張表,製作 Table of Contents
  • 以 frame.html 為主,裡頭紀錄 content 與 body的路徑,因此有相對、絕對路徑兩種設定方式,讀檔時按 frame.html即可。
  • 相對路徑的寫法 1  (檔案一起搬到別的資料匣也能正確開啟)
    • ods html   
    • body="z:\DATA\data.html"       (url='data.html') 
    • contents="z:\DATA\toc.html"   (url='toc.html')
    • frame="z:\DATA\frame.html";
  • 相對路徑的寫法 2
    • ods html   path="z:\DATA\"  (url=none)
    • body="data.html"    
    • contents="toc.html" 
    • frame="frame.html";
  • 絕對路徑的寫法
    •  (URL='某個真的 url') 
    • 需再將三個檔案部署到正確的網址

2014年4月22日 星期二

準備Base programming 筆記_簡單的分析統計

PROC MEANS <DATA=SAS-data-set>
<statistic-keyword(s)> <option(s)>;
  • 預設會出報表,但可用NOPRINT 不出報表。
  • 報表的小數位
    • proc means data=sasuser.diabetes min max maxdec=1;
      run;
  • Group Processing,Class 與 BY
    • Class 不必先 sort,報表集合為一張
    • By 必先sort,報表分成N張,但總分層較多時,速度較快
  • OUTPUT OUT=SAS-data-set STATISTIC=new_variable(s);
    • var arterial heart cardiac urinary;
      output out=test mean=Ave_1 Ave_2 ;
      • Ave_1 Ave_2 是依VAR的順序,先到先贏,即arterial heart ,而 cardiac urinary 就沒有輸出。
      • STATISTIC=new_variable(s) 可指定不只一組,不指定就是全部變項的全部統計值都輸出。

PROC SUMMARY
  • 大致用法同上,但預設無報表,要用 PRINT (option)才會出表

PROC FREQ
  • / nofreq nopercent norow nocol missing
  • tables sex*weight*height;
    N way table 會先以 sex進行分層,輸出weight*height的表(frequency, percent, row pct, column pct)
  • tables sex*weight*height / list;
    只輸出 frequency,與其相關的percent, cumulative frequency, cumulative percent
  • tables sex*weight*height / crosslist;
    以List的方式,輸出與N way table相同的表,支援用 Proc template進行修改。

2014年4月21日 星期一

數字轉文字並保留小數位數

/*數字轉文字並保留小數位數 Converting a Numeric Variable to a Character Variable*/
data tt;
b=131.19;
b1=compress(b);
b2=put(b,6.2);
a=130.00;
a1=compress(a);
a2=put(a,6.2);
run;
image
之前都用 compress的方式,但最大問題是剛好整數(130.00)會變成130!有想過以 length 取得長度,但數值的長度與是否為整數無關,一開始指定best12. ,該欄下的所有 length 就都是12。
因此改用 put 最方便,PUT always return a character
其中參數6.2是指先保留6個位元,其中含兩位小數,輸出後的文字總長即為6位元。

2014年4月20日 星期日

Reading Raw Data File

指定外部資料檔的位置,與讀檔
  • SAS系統檔,Libname
    libname NHIS 'c:\report';
  • 其他檔案,Filename
    • 單檔 filename nhis "z:\DATA\admit.txt";
      nhis 代表實體檔案
      • DATA work.admit;
            infile nhis delimiter='09'x MISSOVER DSD  firstobs=2;
            input ....;
      • filename nhis clear;
    • 多檔 Filename NHIS2 'c:\report\';
      • DATA work.admit;
            infile nhis2(admit.txt) delimiter='09'x MISSOVER DSD  firstobs=2;
            input...;
    • 直接呼叫檔案
      • DATA work.admit;
            infile "z:\DATA\admit.txt" delimiter='09'x MISSOVER DSD  firstobs=2;

Column Input
  • INPUT variable <$> startcol-endcol . . .;
    適用於 Fixed-field Records
    • 條件:固定的n個變項,變項為標準的數字與文字,原始資料要按位子對齊好
    • 指定變項的起點與終點,因此,變項間的順序就不重要了。資料欄位也可被重覆讀取。
  • 用 Infile 
    • libname libref 'SAS-data-library';
      filename nhis "z:\DATA\admit.txt";
    • DATA work.admit;
    • infile "z:\DATA\admit.txt" obs=10 ;
    • input ID 1-10 Name $ 20-30 Sex 15;
    • run;
  • 用 Datalines (Reading Instream Data )
    • DATA work.admit;
    • input ID 1-10 Name $ 20-35 Sex $ 15;
    • DATALINES;
    • 2458          F    Murray, W
    • 2462          M    Almers, C
    • ;
    • 不必再 run
  • Datalines 換行讀取  (僅讀入部分變項)
    • data coat;
    • input category high1-high3 / low1-low3;
    • datalines;
    • 5555 9 8 7 6
    • 4 3 2 1
    • 8888 21 12 34 64
    • 13 14 15 16
    • ;
  • DATA ERROR訊息,不會中斷DATA STEP。

Formatted Input
  • 適用於 Fixed-field Records standard and nonstandard data
    @ n 與 + n  可以交互使用
  • INPUT @n Var-name Informat. ;
    n表示第幾個欄位(position)起
    • input @15 ID $5. @1 LastName $10. @30 Payment 8.
  • INPUT +n Var-name Informat.;
    用+n 要加到變項的起點,要注要讀完一個變項後,column pointer 會自動往後一位,LastName 在第10位End,到第15位的ID時,要 +4 就可以了。
    往回讀資料,要用  + (-n)
    • input LastName $10. +4 ID $5.  +10 Payment 8.
  • Informat 告知 SAS 原始資料的儲存方式,才能順利讀取檔案,但是在 PDV裡,變項不自動以 informat指定格式儲存。
    • PERCENTw.d      w為總長,d為小數位數
    • COMMAw.d
      • 適用在數值卻有  , $ %   等符號 
    • date7.         date9.
      mmddyy8.   mmddyy10.
      datetime.
      TIME8. 

Record Formats
Raw data 儲存observation的方式
  • Fixed-Length Records
    每筆的 end of record marker 都在同一位置 
  • Variable-Length Records
    不固定的 end of record marker
    • 有fixed-field data的,某區段都固定給某變項,例如欄位長固定( 4.)
      PAD option
      • 有些筆數的值較短(ex: 10,還有兩個位元),會提早遇到end of record,避免電腦傻傻執意要換到下列補足長度(另2位元)
      • 本欄為 missing

Free-Format Data
欄位的 begin 與 end 沒有完全固定position
  • List Input與Delimiter(DLM)
    raw data file的限制:數字與文字都只能 8位元,超過會 truncated;標準變項;以空白或符號分隔變項;文字或數字裡不能有該符號;missing要用 . 或其他文字表示。
    • Infile "z:\DATA\admit.txt" DLM=’符號’
      Input
      var1 var2
      var3-var6 
      (var7-var10) ($)   ….. varN ;
  • 解決方案
    • MISSOVER option:某列尾端有Missing value
    • DSD option:某列開頭、列中有missing value
      • 預設Delimiter 為 , 
      • ,, 表示 missing
      • 值的引號”會被移除
    • Length statement:文字大於8位元
      • Infile ….; Length Var $20. ; input Id Var …..;
        注意此時Input裡的 Var 不必再加 $ 了。但因為先以 Length設定,Var是第一個變項,而非 Id
    • & 文字值含有空白(不連續),如 Taipei city
      • 其後的Delimiter 要改為兩個空白「  」
      • Length City $ 12; Input …  city & ;
        或 Input … city & $12. ;
    • : 數值或文字長度超過8,且不內含空白
      • 文字時,需設 Length
      • 數值時,不需設 Length,用 Comma. 即可
        • input name: $13.  pop: Comma.  ;
          datalines;
          TaipeiCity 100,000,000
          KeelungCity 100000000
          ;

讀 Excel 檔
  • libname libref 'location-of-Excel-workbook' <options>;
    • libname readxls "Z:\DATA\finance.xls";
    • proc contents data=readxls._all_ ; run; *可直接知道sheet細詳資訊;
    • data finance ;  set   READXLS."'1$'"n  ;run;
    • libname readxls clear; *停止連結 xls 檔;
  • 可用的 option 
    • DBMAX_TEXT=n
      單欄文字長度
    • GETNAMES=YES|NO
      第一列為變項名
    • MIXED=YES|NO
      所有資料轉成文字,預設是no
    • SCANTEXT=YES|NO
      以最長的列寬為預設列寬。
    • SCANTIME=YES|NO
      no 只有time 的變項 也用 date9.
      yes 改用 time8.
    • USEDATE=YES|NO
      yes date/time 的變項 用 date9.no  改用 datetime.

標準的與非標準的變項
  • 數值型
    • 標準的: 羅馬數字、小數數字、正負號數字、科學記號(ex: E-notation)
    • 非標準的:內含(%$,)、日期時間、分數、二進位、十六進位

建構變項的OPERATOR
  • arithmetic operator,依優先順序
    • -(負號)、**(指數)
    • 乘除
    • 加減
  • Comparison Operators
    • > < = ^= >= <=
    • in ( 1 ,2 ,3) 或  in ( 1 2 3) 
    • in ( "LINK" , "Value" )
  • Logical Operators
    • AND & ,  OR  | ,  NOT ^ 
      • 用 OR的注意事項
        • if TimeMin<12 or 14; 
          • OR 前後要分開看, 2 一定是 true,本條件形同虛設
        • if TimeMin<12 or TimeMin=14;
          • 會輸出 <12 還有 =14 的。

新增日期、時間變項 (待續補充)
  • 日期(兩位年從1920起至2019)
    •                   Date='01jan2014'd;              Date='01jan14'd;
    • 以上可選  attrib date format=date9.; 或 attrib date format=date7.;
    • 或            attrib date format=mmddyy10.;   attrib date format=mmddyy8.;
                      01/01/2014                                 01/01/14
  • 時間 
    • Time='21:00't;
    • attrib TIME format=TIME8.;  21時0分0秒
  • Datetime
    • DateTime='01jan2014:21:00:00'dt;
    • attrib DateTime format=datetime.;

輸出Raw Data File
  • 把sas dataset 轉成 依 column 對齊的 txt檔
    • data _null_;
    • set sasuser.admit;
    • file "z:\admit_column.txt"; *沒有 file 就 put 到 log裡;
    • Put
    •   ID  4.
    •   @6 Name  15.    /* 用 @ 位置  VAR  長度  比較不會出錯  */
    •   @22 Sex  1.
    • run;
  • Sas dataset 轉成 Free-Format raw data;
    • PUT variable <: format>;
      • file …;  Put ID  Fee: 7.2 ;
    • DLM=’’
      • file … DLM=’,’;
    • DSD
      • file … DSD;
      • 預設Delimiter 為 ,
      • 有 , 的數值,會包在一組雙引號中
    • PROC EXPORT DATA=SAS-data-set;
      OUTFILE=filename <DELIMITER='delimiter'>;
      RUN;
  • 存到 xls 檔的 sheet
    • libname readxls "Z:\DATA\finance.xls";
    • data readxls.admit;
    • set sasuser.admit; *不必用 'admit$'n ;
    • run;

運用filename, PIPE, infile 與 windows語法互動, 參考Back Up with Each Submit and Save Your Sanity
    • filename backup pipe 'dir C:\backup /t:w /a:-d /OD';
    • data backup;
    •  infile backup missover pad length=len;
    •  input @01 line $varying200. len; 
    • run; 
    •  

    2014年3月24日 星期一

    SAS 9.3 64位元與 Win 7 64位元,無法讀取匯入 Excel(xls, xlsx)或 Access (mdb, accdb)


    問題描述:
    作業系統環境是 Win7 64 與 SAS 9.3 64位元,Office 為 2003 版的,使用以下方式讀取或匯出 Excel 或Access的檔案
    • Import Wizard
    • Proc import 或Proc export
      • PROC IMPORT DBMS=EXCEL 
                    DATAFILE= "\directory\filename.xls" 
                   OUT= WORK.cdc REPLACE;
             SHEET="Sheet1";
             GETNAMES=YES;
             MIXED=NO;
             SCANTEXT=YES;
             USEDATE=YES;
             SCANTIME=YES;
        RUN;
    • Libname
      • libname myref  "\directory\filename.xls";
    會失敗,而Log檔訊息為
    ERROR: Connect: 類別未登錄
    ERROR: Error in the LIBNAME statement.
    ERROR: Error trying to establish connection: Unable to create Data Source.: Class not registered
    ERROR: Error in the LIBNAME statement.
    此狀況常見於剛換系統,以前寫的sas碼都變得無法執行。

    解決方式:
    • 換回 SAS 9.3 的 32位版,但工程較大 ,但也一樣要安裝SAS PC Files Server
    • 使用SAS PC 檔案伺服器(SAS PC Files Server)來讀取檔案,建議SAS 64位元用戶一定要裝。
    1. 安裝方式請參考 SAS® 9.3 FOUNDATION for Windows 安裝導引
    2. 安裝過程中,一定要選擇讓 SAS PC Files Server隨windosw 自行啟動,否則後續每次叫檔案要自行到「所有程式」手動啟動
    3. 讀檔或匯出檔案的程式碼要稍微改如下
    4. libname myref pcfiles server="localhost" 
      port=9621
      path="\directory\filename.xls";
      proc import dbms=excelcs
            datafile='\directory\filename.xls' 
            out=sas-data-output-filename replace;
         sheet='sheet-name';
         server="localhost";
         port=9621 ;
      run;
      如此,只要更動少部分的程式即可!
        如果有進一步問題,可參考:http://support.sas.com/kb/33/228.html
      或是 http://support.sas.com/kb/43/802.html

    2014年2月22日 星期六

    準備Base programming 筆記_Day 1

    雖然已有3、4 年的SAS經驗,但不希望浪費 Base programming for SAS 那近 六張小朋友的報名費,為求謹慎,我依照  SAS Certification Prep Guide: Base Programming for SAS 9, Third Edition 這本書,開始按步就班進行準備,但又因為不想在書裡留下任何記號,就決定把筆記留在blogger裡,以供後續參考。

    期許自己每晚能定時 K書,別估負那貴松松的書籍費和報名費 ( 搭廉航去日本爽爽玩的來回機票就這般沒了~~~ T_T 越想越心痛 )。

    ====================================================================

    程式以 DATA 或 Proc 為一組,執行上遇到DATA或Proc時,會把已讀入的指令執行完畢,再去讀新的一組DATA 或 Proc指令。

    Two-level 資料檔名稱 ( Libname.filename )
    • 開頭,letter (A~Z)大小寫不拘,或者 underscore (_)
    • 之後,任意 letter underscore 或數字。
    • 長度,
      • Libname :最多8碼
      • Filename:長度最多32碼。
    Missing Value
    數值變項為 (.),文字變項為單純的空白()  。

    變項的 Format ,用於 Display
    作用規則 SAS data value --> sas format --> Formatted sas data value
    例如:把 數值的5678,用DOLLAR8.2 format,就變成以 $5,678.00 呈現。
    8.2 就是原自 w.d 的寫法,w是總長度,d是含有小數幾位。

    變項的 Informat ,用於 Read data
    作用規則 Data value --> sas informat --> sas data value
    例如, 原始外部資料是 $5,678.00 ,指定以Comma 10. 去讀,電腦最終以5678.00 轉入SAS,去除 $ 和 ,。

    有關 format 和 informat,一個顯示資料,一個讀取資料,後續應該會有更細的介紹。

    一個(;)表示一個statement,下例有5個(;),是5個statement。(@_@ 還真的沒有仔細算過)
    proc print data=new.prodsale
    label noprint;
    var x y z ; where state='NC';
    label state='Name of State'; run;


    附註:除上述所列,還有一些很基本的軟體環境,一般user 都已知道,速速往後讀吧。