【问题标题】:Replacing missing values by previous observation with conditions (R or SAS)用条件(R 或 SAS)替换先前观察的缺失值
【发布时间】:2017-08-06 16:35:59
【问题描述】:

我有 persion-period 数据集,我正在尝试创建与时间相关的协变量。 目前我的数据看起来像这样。变量 chg & help 只是我在创建这些数据时创建的变量。

ID time status chg help parent married child 
1 0 P 0 . 0 0 0
1 1 P 0 . 0 0 0
1 2 P 1 . 0 0 0
1 3 M 0 P 1 0 0
1 4 M 0 . 0 0 0
1 5 M 0 . 0 0 0
1 5 M 0 . 0 0 0
2 0 P 0 . 0 0 0
2 1 P 1 . 0 0 0
2 2 L 0 P 1 0 0
2 3 L 0 . 0 0 0
2 4 L 1 . 0 0 0
2 5 M 0 L 0 1 0
2 6 M 0 . 0 0 0 

我正在尝试“保存”这些协变量(父母子女已婚),例如,如果在时间 t=3,父母=1,那么在时间 t=4(以及跟进结束),父母变量应保持在 parent=1。

所以正确的数据应该是这样的

ID time status chg help parent married child 
1 0 P 0 . 0 0 0
1 1 P 0 . 0 0 0
1 2 P 1 . 0 0 0
1 3 M 0 P 1 0 0
1 4 M 0 . 1 0 0
1 5 M 0 . 1 0 0
1 6 M 0 . 1 0 0
2 0 P 0 . 0 0 0
2 1 P 1 . 0 0 0
2 2 L 0 P 1 0 0
2 3 L 0 . 1 0 0
2 4 L 1 . 1 0 0
2 5 M 0 L 1 1 0
2 6 M 0 . 1 1 0 

非常感谢任何有关 R 或 SAS 的帮助!

【问题讨论】:

    标签: r sas


    【解决方案1】:

    R中,我们可以得到按'ID'分组后感兴趣的变量的累积和(cumsum

    library(data.table)
    setDT(df1)[, (6:8) := lapply(.SD, cumsum), ID, .SDcols = parent:child]
    df1
    #    ID time status chg help parent married child
    # 1:  1    0      P   0    .      0       0     0
    # 2:  1    1      P   0    .      0       0     0
    # 3:  1    2      P   1    .      0       0     0
    # 4:  1    3      M   0    P      1       0     0
    # 5:  1    4      M   0    .      1       0     0
    # 6:  1    5      M   0    .      1       0     0
    # 7:  1    5      M   0    .      1       0     0
    # 8:  2    0      P   0    .      0       0     0
    # 9:  2    1      P   1    .      0       0     0
    #10:  2    2      L   0    P      1       0     0
    #11:  2    3      L   0    .      1       0     0
    #12:  2    4      L   1    .      1       0     0
    #13:  2    5      M   0    L      1       1     0
    #14:  2    6      M   0    .      1       1     0
    

    【讨论】:

      【解决方案2】:

      SAS中,可以使用RETAINLAST.varible得到累计和。

      Data origin_dataset;
          infile 'Your raw data folder';
          input ID time status $ chg help $ parent married child;
      Run;
      
      Data temp;
          Set origin_dataset;
          By ID;
          Retain parent_t married_t child_t;
          parent = SUM(parent_t, parent); parent_t = parent;
          married = SUM(married_t, married); married_t = married;
          child = SUM(child_t, child); child_t = child;
          If LAST.ID = 1 Then DO;
              parent_t = 0;
              married_t = 0;
              child_t = 0;
          END;
      Run;
      
      Proc print data = temp (drop = parent_t married_t child_t);
      Run;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多