【问题标题】:SAS merging/condensing dataSAS 合并/压缩数据
【发布时间】:2013-10-09 08:50:00
【问题描述】:

我有一个类似于下面的数据集

ID  A   B  C  D  E
1   1
1          1
1       1
2       1
2             1
3                1
3   1
4          1
5       1

我想将每个 ID 的数据压缩成一行。因此,数据集将如下所示。

ID  A   B  C  D  E
 1  1   1  1 
 2      1     1
 3  1            1
 4         1
 5      1

我创建了另一个表并删除了重复的 ID。所以我有两个表——A 和 B。然后我尝试将两个数据集合并在一起。我在玩下面的 SAS 代码。

data C; 
     merge A B; 
     by ID;
run; 

【问题讨论】:

  • 请展示您尝试过的内容 - 我们在这里帮助您解决代码问题,但我们不会为您编写代码
  • 如果您没有在问题中发布您尝试过的内容,我们将无法帮助您,您的问题可能会被删除

标签: sas


【解决方案1】:

这是我从另一个论坛中学到的一个巧妙的技巧。无需拆分原始数据集,第一个更新语句创建结构,第二个更新值。 BY 语句可确保每个 ID 仅获得 1 条记录。

data have;
infile datalines dsd;
input ID  A   B  C  D  E;
datalines;
1,1,,,,,
1,,,1,,,
1,,1,,,,
2,,1,,,,
2,,,,1,,
3,,,,,1,
3,1,,,,,
4,,,1,,,
5,,1,,,
;
run;

data want;
update have (obs=0) have;
by id;
run;

【讨论】:

    【解决方案2】:

    这可以使用retain 语句来解决。

    data B(rename=(A2=A B2=B C2=C D2=D));
      set A;
      by id;
      retain A2 B2 C2 D2;
      if first.id then do;
        A2 = .;
        B2 = .;
        C2 = .;
        D2 = .;
      end;
      if A ne . then A2=A;
      if B ne . then B2=B;
      if C ne . then C2=C;
      if D ne . then D2=D;
      if last.id then output;
      drop A B C D;
    run;
    

    还有其他方法可以解决这个问题,但希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      PROC MEANS 是处理此类事情的绝佳工具。 PROC SQL 也会给你一个合理的解决方案,但 MEANS 更快。

      proc means data=yourdata;
      var a b c d e;
      class id;
      types id; *to avoid the 'overall' row;
      output out=yourdata max=; *output the maximum of each var for each ID - use SUM instead if you want more than 1;
      run;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-30
        • 1970-01-01
        • 2018-11-29
        • 1970-01-01
        • 2018-07-01
        • 2017-03-26
        • 1970-01-01
        相关资源
        最近更新 更多