【问题标题】:in a SAS data step referencing another data set without a merge?在没有合并的情况下引用另一个数据集的 SAS 数据步骤?
【发布时间】:2019-07-31 15:32:37
【问题描述】:

感谢反馈,我仍然是通知程序员。我正在尝试在 SAS 中编写以下代码。

我有两个数据集 a) 和 b),包含以下变量:

a) Bene_ID, county_id_1, county_id_2, county_id_3 etc (it's 12 months) 
b) county_ID, rural (yes/no) 

我通常会在数据步骤中创建一个数组:

Array country (12) county_ID_1- county_ID_12 

并通过对 bene_ID 进行分组处理,以输出长(标准化)数据集,如下所示:

   bene_id, month 1, county_id 
    bene_id, month 2, county_id
    bene_id, month 3, county_id 

等等

但是,我如何在数据步骤中访问其他数据集 b)?拉进农村变数?这就是我想要的:

bene_id, month 1, county_id, if rural = "yes"
bene_id, month 2, county_id, if rural = "yes"
bene_id, month 3, county_id, if rural = "yes"

我尝试在此公告板上寻找其他类似的问题,但我什至不确定要搜索的正确术语。我不想进行完全合并的原因是:如何过滤数组值?例如当农村=“不”?

谢谢大家, 萝莉

【问题讨论】:

    标签: sas


    【解决方案1】:

    这是一个使用 FORMAT 会有所帮助的示例。您可以使用第二个数据集创建格式

    data formats;
      retain fmtname 'rural';
      set b;
      rename county_id=start rural=label;
    run;
    
    proc format cntlin=formats ;
    run;
    

    然后在处理第一个数据集时使用该格式。

    data want ;
      set A;
      array county_id_ [12];
      do month=1 to dim(county_id_);
        county=county_id_[month];
        rural = put(county,rural3.);
        output;
      end;
      drop county_id_: ;
    run;
    

    【讨论】:

    • 谢谢!我想知道这是否是正确的方法。非常感谢。
    【解决方案2】:

    您正在将数据结构从宽(数组形式)转换为高(分类形式)。这通常称为枢轴或转置。转换将存储在每个数组元素 name(列)中的信息转换为可在行级别访问的数据。

    您可以将转置与县合并以选择农村。

    * 80% of counties are rural;
    data counties;
      do countyId = 1 to 50;
        if ranuni(123) < 0.80 then rural='Yes'; else rural='No';
        output;
      end;
    run;
    
    * for 10 people track with county they are in each month;
    data have;
      do personId = 1 to 10;
        array countyId (12);
        countyId(1) = ceil(50*ranuni(123));
        do _n_ = 2 to dim(countyId);
          if ranuni(123) < 0.15 then 
            countyId(_n_) = ceil(50*ranuni(123)); * simulate 15% chance of moving;
          else
            countyId(_n_) = countyId(_n_-1) ;
        end;
        output;
      end;
    run;
    
    proc transpose data=have out=have_transpose(rename=(col1=countyId)) ;
      by personId;
      var countyId:;
    run;
    
    proc sort data=have_transpose;
      by countyId personId;
    run;
    
    data want_rural;
      merge have_transpose(in=tracking) counties;
      by countyId;
      if tracking and rural='Yes';
      month = input(substr(_name_, length('countyId')+1), 8.);
      drop _name_;
    run;
    

    如果您的宽数据还有一组额外的 12 列,例如每个月支付的一组金额,最好的方法是像 @Tom 所示进行“数据步骤”转置,并在循环

      amount = amount_[month];
    

    【讨论】:

      猜你喜欢
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      相关资源
      最近更新 更多