Find first non-missing str value in panel & use value to forward and back fill by group (SAS or PROC SQL)

后端 未结 2 865
温柔的废话
温柔的废话 2021-01-22 11:36

I have a data set containing an unbalanced panel of observations, where I want to forward and backward fill missing and/or \"wrong\" observations of ticker with the latest non-m

2条回答
  •  暖寄归人
    2021-01-22 12:09

    You can do this several ways, but proc sql with some nested sub-queries is one solution.

    (Read it from inside out, #1 then 2 then 3. You could build each subquery into a dataset first if it helps)

    proc sql ;
      create table want as 
      /* #3 - match last ticker on id */
      select a.id, a.time, a.ticker_have, b.ticker_want
      from have a
           left join
            /* #2 - id and last ticker */
           (select x.id, x.ticker_have as ticker_want
            from have x
                 inner join
                  /* #1 - max time with a ticker per id */
                 (select id, max(time) as mt
                  from have
                  where not missing(ticker_have)
                  group by id) as y on x.id = y.id and x.time = y.mt) as b on a.id = b.id
      ;
    quit ;
    

提交回复
热议问题