2016-10-26 45 views
1

我想提取所有第n行數據集,然後提取每個後續​​第33行,並將它們存儲在新數據集中。提取數據集的每第n行

我有一個包含n倍33個估計所附下面彼此,我希望向所有估計a0的提取到一個稱爲A0和數據集,那麼所有的a1估計到的數據集A1等等,直到我有33的數據集數據集。

我可以爲每個元素做到這一點,但這需要很多代碼,我想簡化它。這是命名數據集的代碼,然後將所有元素提取到它中。

data a0; 
set _parest1; 
if mod(_n_,33) = 1; 
run; 

這是一個特定的問題,是一個大問題的一部分。我有許多包含34個估計參數(a0,a1 ... a33)的數據集,我想要對每個估計值進行均值。

回答

1

使用firstobs=數據集選項從第n條記錄開始;

data want; 
set have(firstobs=10); 
if _n_ = 1 then output; 
else if mod(_n_,33) = 1 then output; 
run; 

因此,要循環使用宏。例如:

data test; 
do i=1 to 100; 
output; 
end; 
run; 

%macro loop_split(n,mod, ds, outPre); 
%local i j; 
%do i=1 %to &n; 
    %let j=%eval(&i-1); 
    data &outPre&j; 
    set &ds(firstobs=&i); 
    if _n_ = 1 then output; 
    else if mod(_n_,33) = 1 then output; 
    run; 
%end; 
%mend; 

%loop_split(33,33,test,want); 

我分裂nmod值作爲他們不必是相同的,但在你的情況。

+0

感謝您的快速回答,不幸的是,我沒有清楚我想要什麼所以編輯了我的問題,在你的例子中,你從10開始,然後採取下一個2x33線,但我希望能夠從11開始,然後採取下一個2x33線,然後12等,我怎麼能得到33數據集? –

+0

我明白了,你可以用宏包裝這個,給我一分鐘,我會爲你編輯的 – DomPazz

+0

非常好 - 謝謝 –

2

這是另一種方式來做到這一點:哈希方法的散列。這很大程度上取決於Paul Dorfman關於該主題的論文Data Step Hash Objects as Programming Tools

data estimates; 
    do id = 1 to 50; 
    output; 
    end; 
run; 

data _null_; 
    if 0 then set estimates; 
    length estimate 8; 
    if _n_=1 then do; 
    declare hash e(); 
    declare hash h(ordered:'a'); 
    h.defineKey('estimate'); 
    h.defineData('estimate','e'); *this 'e' is the name of the other hash!; 
    h.defineDone(); 
    declare hiter hi('h'); 
    end; 
    do _n_ = 1 by 1 until (eof); 
    set estimates end=eof; 
    estimate = mod(_n_-1,5); 
    rc_h = h.find(); 
    if rc_h ne 0 then do; 
     e = _new_ hash(ordered:'a'); 
     e.defineKey('estimate','id'); 
     e.defineData('estimate','id'); 
     e.defineDone(); 
     h.replace(); 
    end; 
    e.replace(); 
    end; 

do rc = hi.next() by 0 while (rc = 0) ; 
    e.output (dataset: cats('out',estimate)) ; 
    rc = hi.next() ; 
end ; 
run; 

這可以讓你任意輸出任意數量的數據集,這很好。這裏你用33代替5並調整變量名稱('估計'是估計數字,我用MOD計算,但也許你已經在數據集中了,'id'當然是你的ID是那行的 - a行號是好的,如果你有其他數據變量(你可能會這樣做),你可以將它們添加到defineData中,以便e