sas循环遍历数据集会使值丢失,具体取决于第一行

时间:2017-10-25 17:36:30

标签: sas

我有一个与此类似的数据集。我不确定我会获得多少个库存或行,因为它是代码的一部分。但我将第一个值等于0桶。

DATA MY_data;
INPUT bucket D_201503 D_201504 ;
DATALINES;
0 1000 20500
1 200 6700
2 101 456
3 45 567
;

例如 - 在此数据集中,我希望缺少第一行值低于10%的值。例如,对于桶0,第一个值是1000,因此应该缺少45个。对于20500也是如此。应该丢失低于10%的任何东西。数据集通常不是很大,但需要确定列和行。 所以我应该把它作为

0 1000 20500
1 200 6700
2 101 .
3 . .

我不确定如何遍历数据集并制作此条件

3 个答案:

答案 0 :(得分:1)

DATA MY_data;
INPUT bucket D_201503 D_201504 ;
DATALINES;
0 1000 20500
1 200 6700
2 101 456
3 45 567
;

data want;
set MY_data;
array row(*) _all_;
array _first_row(999); /*any number >= the number of columns of MY_data*/
/*we read the first line and store the values in _first_row array*/
retain _first_row:;
if _n_ = 1 then do i=1 to dim(row);
    _first_row(i) = row(i);
end;
/*replacing values <10% of the first row*/
else do i=1 to dim(row);
    if upcase(vname(row(i))) ne "BUCKET" and row(i) < 0.1*_first_row(i) then row(i) = .;
end;
drop i _first_row:;
run;

答案 1 :(得分:0)

/*Find out how many variables there are (assume we just want all vars prefixed D_)*/
data _null_;
  set my_data(obs = 1);
  array vars_of_interest(*) D_:;
  call symput(dim(vars_of_interest),"nvars")
run;

/*Save bucket 0 values to a temp array, compare each row and set missing values*/    
data want;
  set my_data;
  array bucket_0(&nvars) _temporary_;
  array vars_of_interest(*) D_:;
  do i = 1 to &nvars;
    if bucket = 0 then bucket_0[i] = vars_of_interest[i];
    else if vars_of_interest[i] < bucket_0[i] / 100 then call missing(vname(vars_of_interest[i]))
  end; 
run;

答案 2 :(得分:0)

您需要一种方法来记住第一行(或者可能是BUCKET = 0的行?)的值,以便您可以将第一行的值与当前值进行比较。暂时的ARRAY是一种简单的方法。

因此,假设BUCKET始终是数据中的第一个数字变量,那么您可以这样做。

data want ;
  set my_data;
  array x _numeric_;
  array y (1000) _temporary_;
  do i=2 to dim(x);
    if bucket=0 then y(i)=x(i);
    else if x(i) < y(i) then x(i)=.;
  end;
  drop i;
run;

如果BUCKET不是第一个变量,那么您可以在retain bucket;语句之前添加set以强制它成为第一个变量。或者更改第一个数组语句以列出要处理的特定变量,只需记住更改DO循环的下限。

如果你有超过一千个变量,那么增加临时数组的维度。