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