天天看点

《非哥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;
           

总结:实现了在任意位置插入任意行任意数据的功能。