【问题标题】:Carrying previous value forward when missing value in SAS在 SAS 中缺少值时将先前的值向前推进
【发布时间】:2019-02-08 19:26:38
【问题描述】:

我有以下数据集:

Player     Average1      Average2      Average3
001        .283          .             .302
002        .256          .             .
003        .314          .             .297
004        .282          .274          .

我希望数据集如下所示:

Player     Average1      Average2      Average3
001        .283          .283          .302
002        .256          .256          .256
003        .314          .314          .297
004        .282          .274          .274

该表扩展到Average24。我熟悉如何使用 dplyr 包对 R 中的一行执行此操作,但不使用 SAS。

R:

Data = DATA %>% mutate(Average2 = ifelse(is.na(Average2), Average1, Average2))

【问题讨论】:

    标签: loops sas missing-data


    【解决方案1】:

    通过这种结构,您可以使用 ARRAY。

    data want;
      set have;
      array averages average1-average3 ;
      do _n_=2 to dim(averages);
        averages(_n_)=coalesce(averages(_n_),averages(_n_-1));
      end;
    run;
    

    垂直结构会更容易。然后您可以使用UPDATE 语句来实现LOCF(Last Observation Carried Forward)操作。

    data have ;
      input player @;
      do rep=1 to 3 ;
         input average @;
         output;
      end;
    cards;
    001        .283          .             .302
    002        .256          .             .
    003        .314          .             .297
    004        .282          .274          .
    ;
    data want;
      update have(obs=0) have;
      by player;
      output;
    run;
    

    【讨论】:

      【解决方案2】:

      使用coalesce 函数,它将为给定列表中的变量分配第一个非缺失值:

      Average2=coalesce(Average1,Average2,Average3);
      

      如果你愿意,你可以进一步对所有 24 个变量使用数组循环,而不是手动编写

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-15
        相关资源
        最近更新 更多