我會首先建議Base SAS並不真正以這種方式工作,通常情況下,這並不是說它不能,但通常你可以解決大多數問題而不指向特定的行。
所以,雖然這個答案會解決你明確的問題,但它可能不是在真實世界的場景中有用;通常在現實世界中,你需要一個匹配鍵或除了「行號」以外的其他元素才能結合使用,如果你這樣做了,那麼你可以更有效地做到這一點。您也可能會重新安排您的數據結構,使其更方便。
這就是說,你給的具體例子很簡單:
data have;
input ID Number;
datalines;
1 2
2 5
3 6
4 1
;;;;
run;
data want;
set have;
_t = 3;
set have(rename=number=number3 keep=number) point=_t ;
number2=number+number3;
run;
如果你有SAS/IML(SAS的矩陣語言),這有點類似R,那麼這既是一個非常不同的故事您執行此操作的可能性以及您如何執行此操作的可能性。
proc iml;
a= {1 2, 2 5, 3 6, 4 1}; *create initial matrix;
b = a[,2] + a[3,2]; *create a new matrix which is the 2nd column of a added
elementwise to the value in the third row second column;
c = a||b; *append new matrix to a - could be done in same step of course;
print b c;
quit;
爲了與首先觀察做到這一點,這是一個容易得多。
data want;
set have;
retain _firstpoint; *prevents _firstpoint from being set to missing each iteration;
if _n_ = 1 then _firstpoint=number; *on the first iteration (usually first row) set to number's value;
number = number - _firstpoint; *now subtract that from number to get relative value;
run;
我會詳細闡述一下。 SAS按記錄級別工作,每個記錄在DATA步驟中獨立處理。 (另一方面,PROC可能不會這樣做,儘管許多程序都在某種程度上)。與SQ1和類似的數據庫一樣,SAS並不真正承認任何行是「第一」或「第二」或「第n」;然而,與SQL不同的是,它可以讓你假裝它是基於當前排序的。 POINT =隨機存取方法是這樣做的一種方式。
不過,大多數情況下,您將使用數據中的某些內容來確定要執行的操作,而不是與數據排序有關的操作。這裏有一種方法可以和POINT =方法做同樣的事情,但是使用ID的值:
data want; if n = 1 then set(其中=(ID = 3)rename = number = number3); 集有; number2 = number + number3; 跑;
在數據步驟(_N_
= 1)的第一次迭代取行具有從其中Id = 3,然後取線從具有爲了(實際上它並不此:)
*check to see if _n_=1; it is; so take row id=3;
*take first row (id=1);
*check to see if _n_=1; it is not;
*take second row (id=2);
... continue ...
自動保留SET語句中的變量,因此NUMBER3會自動保留(yay!),並且在數據步驟循環的迭代之間不會丟失。只要您不修改該值,它就會保留每次迭代。
來源
2013-03-19 21:13:17
Joe
你有SAS/IML還是SAS? – Joe 2013-03-19 21:05:15