【问题标题】:Pick random observation for each by group in SAS在SAS中为每个组选择随机观察
【发布时间】:2016-06-30 22:33:57
【问题描述】:

我有两个数据集:formpool 具有相似的表结构。

a) 数据集表格

b) 数据集

  • 上述两个数据集有三列,其中 KeyLevel 组合在 form 数据集有 4 行。

  • 还有 Sub-Level 数据在 formpool 数据在 KeyLevel 级别是互斥的。

  • Sub-Level 值具有分配给它们的特定 Level,即 LevelSub-Level 遵循一个层次结构。

我想在 formSub-Level 列下填充 null 值 pool 数据集中具有 Sub-Level 值的数据集,其中 Sub-Level > pool 数据集中应该属于相同的 KeyLevel form 数据集。

如何在 SAS 中做到这一点?

EDIT 1null 值 填充在 form 数据集中必须在每个数据集中是不同的或唯一的键、级别组。

【问题讨论】:

  • 标题和标签中都提到的随机性成分是从哪里来的?
  • @superfluous:从“pool”数据集中随机选择 Sub_Level 时出现随机性,以在“form”表的“Sub-Level”列中填充空值。

标签: random sas


【解决方案1】:
  1. form中创建一个新的行ID:keylevelnew_id
  2. 在组级别随机排序pool 并创建相同的ID。
  3. 通过keylevelnew_id 左连接并替换缺失值。

由于与pool 相比,form 中每个组的值更少或相等,并且所有值都是分离且唯一的,您将完成form 而不会生成重复项。

代码示例:

data form;
  set form;
  retain new_id;
  if first.level then new_id = 0;
  new_id + 1;
run;
data pool;
  set pool;
  ran_num = ranuni(12345); /* generate random uniform number */
run;
proc sort data=pool; by key level ran_num; run; /* sort by random number */
data pool;
  set pool;
  retain new_id;
  if first.level then new_id = 0;
  new_id + 1;
run;
proc sql;
create table form_full as
  select a.key, a.level, coalescec(a.sub_level,b.sub_level) as sub_level
    from form a
      left join pool b
        on a.key eq b.key and a.level eq b.level and a.new_id eq b.new_id
      ;
quit;

编辑: 如果pool 在组中的行数少于form, 将new_id 更改为form

data form;
  set form;
  retain new_id;
  if first.level then new_id = 0;
  if sub_level ne . then new_id + 1;
run;

【讨论】:

  • 感谢您的回复,但我认为我之前的问题错过了我在原始问题的“编辑 1”中包含的另一个约束。实际上,替换的值在“key”和“level”组中也必须是唯一的。如果您能提供帮助,将不胜感激
  • 我相应地调整了答案。
  • 感谢@Jetzler :帮助!
猜你喜欢
  • 1970-01-01
  • 2018-03-28
  • 1970-01-01
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
  • 2013-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多