1

SASに毎日のデータを含むデータセットがあります。前月のIDとの差をとって、これを月次形式に変換したいと思います。例えば:

thedate, id, val
2012-01-01, 1, 10
2012-01-01, 2, 14
2012-01-02, 1, 11 
2012-01-02, 2, 12
...
2012-02-01, 1, 20
2012-02-01, 2, 15

出力したい:

thedate, id, val
2012-02-01, 1, 10
2012-02-01, 2, 1
4

2 に答える 2

2

これが1つの方法です。SAS-ETS のライセンスを取得している場合は、PROC EXPAND を使用するより良い方法があるかもしれません。

*Setting up the dataset initially;
data have;
informat thedate YYMMDD10.;
input thedate id val;
datalines;
2012-01-01 1 10
2012-01-01 2 14
2012-01-02 1 11 
2012-01-02 2 12
2012-02-01 1 20
2012-02-01 2 15
;;;;
run;

*Sorting by ID and DATE so it is in the right order;
proc sort data=have;
by id thedate;
run;

data want;
  set have;
  retain lastval;  *This is retained from record to record, so the value carries down;
  by id thedate;
  if (first.id) or (last.id) or (day(thedate)=1); *The only records of interest - the first record, the last record, and any record that is the first of a month.;

  * To do END: if (first.id) or (last.id) or (thedate=intnx('MONTH',thedate,0,'E'));
  if first.id then call missing(lastval); *Each time ID changes, reset lastval to missing;
  if missing(lastval) then output; *This will be true for the first record of each ID only - put that record out without changes;
  else do;
    val = val-lastval; *set val to the new value (current value minus retained value);
    output;  *put the record out;
  end;
  lastval=sum(val,lastval); *this value is for the next record;
run;
于 2013-03-07T18:03:25.797 に答える
0

これは、PROC SQL と intnx 関数を使用して先月の日付を 1 か月進めることで実現できます...

proc sql ;
  テーブルラグを次のように作成します
  b.thedate、b.id、(b.val - a.val)をvalとして選択
  mydata b から
       左結合
       mydata a on b.date = intnx('month',a.date,1,'s')
               および b.id = a.id
  b.date、b.idで並べ替えます。
終了する ;

これは、前の月が存在しないシナリオ、または前の月とは異なる日数を持つ月を処理するために微調整が必​​要になる場合があります。

于 2013-03-08T11:46:49.667 に答える