天天看點

《非哥SAS程式設計》在任意位置插入一行資料

在SAS中如何在任意位置插入一行資料呢?

上代碼:

data test_data;
   set s;
   /*output;*/
   if _n_ = 8 then do;
   		do i=1 to 3;
			call missing(of x1-x46);
	   		x1='飛哥';
			x2='男';
			/*output;*/		
		end;
	end;
           

這段代碼,重點在于沒有output,那麼每行的觀測會在data步執行一遍才會寫入。set s先将s中的所有變量寫入記憶體即pdv,s中的變量包含x1和x2。執行到第八行時,x1和x2的值會被覆寫。call missing(of x1-x46)是将x1-x46的變量置為空值。這段程式的運作結果如下。

《非哥SAS程式設計》在任意位置插入一行資料

第八行原來的結果被覆寫,沒有展現出do i=1 to 3;循環的效果,do循環是為了連續插入三行。此時我沒的重點來了。改成如下代碼。

data test_data;
   set s;
   output;
   if _n_ = 8 then do;
   		do i=1 to 3;
			call missing(of x1-x46);
	   		x1='飛哥';
			x2='男';
			output;		
		end;
	end;
           

加上output,set s讀取一行觀測,随即寫入。然後到第八行,進入循環,先設定一行空值,接着把x1,x2指派,随即利用output寫入,即實作了插入的效果。

《非哥SAS程式設計》在任意位置插入一行資料

再來一個重點。

data test_data;
       set s;
	   output;
       if _n_ = 8 then do;
	   		do i=1 to 3;
				call missing(of x1-x46); /*這句改為call missing(of _all_);
		   		x1='飛哥';
				x2='男';
				output;		
			end;
		end;
           

如果更改就會進入死循環,原因是SAS會将i寫入資料集,但是

call missing(of all)将i的值更改為空是以進入死循環。為了避免寫出完美代碼。

data test_data;
       set s;
	   output;
       if _n_ = 8 then do;
			call missing(of _all_); 
		   		x1='飛哥';
				x2='男';
				do i=1 to 3;
					output; /*将x1='飛哥',x2='男';的觀測輸出三遍*/		
				end;
		end;
           

總結:實作了在任意位置插入任意行任意資料的功能。