2016-10-26 46 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