【问题标题】:Summing vertically across rows under conditions (sas)在条件下跨行垂直求和 (sas)
【发布时间】:2013-11-04 00:26:15
【问题描述】:

县...AgeGrp...人口

A.............1........200

A.............2........100

A.............3........100

一个............所有............400

B.............1........200

所以,我有一个县列表,我想找到每个县的 18 岁以下人口占人口的百分比,所以作为上表中的一个例子,我想只添加以下人口agegrp 1 和 2 并除以“所有”人口。在这种情况下,它将是 300/400。我想知道是否每个县都可以这样做。

【问题讨论】:

    标签: sas


    【解决方案1】:

    我们称您的 SAS 数据集为“HAVE”,并假设它有两个字符变量(CountyAgeGrp)和一个数字变量( 人口)。假设您的数据集中总是有一个观察值,每个 CountyAgeGrp='All' 的值是 Population 的总和县。

    为了安全起见,让我们按县对数据集进行排序并在另一个数据步骤中对其进行处理,创建一个名为“WANT”的新数据集,其中包含县人口的新变量( TOT_POP),你想要的两个年龄组值的总和(TOT_GRP)并计算比例(AgeGrpPct):

    proc sort data=HAVE;
       by County;
    run;
    data WANT;
       retain TOT_POP TOT_GRP 0;
       set HAVE;
          by County;
    
       if first.County then do;
          TOT_POP = 0;
          TOT_GRP = 0;
          end;
    
       if AgeGrp in ('1','2') then TOT_GRP + Population;
       else if AgeGrp = 'All' then TOT_POP = Population;
    
       if last.County;
       AgeGrpPct = TOT_GRP / TOT_POP;
    
       keep County TOT_POP TOT_GRP AgeGrpPct;
       output;
    run;
    

    请注意,包含 AgeGrp='All' 的观察并不是真正需要的;您也可以创建另一个变量来收集所有年龄段的总和。

    【讨论】:

      【解决方案2】:

      如果您想要一种程序方法,请为 18 岁以下的人创建一个格式,然后使用 PROC FREQ 来计算百分比。有必要使用此方法从数据集中排除“所有”值(在源数据中包含汇总行通常是不好的做法)。 PROC TABULATE 也可以用于此。

      data have;
      input County $ AgeGrp $ Population;
      datalines;
      A 1 200
      A 2 100
      A 3 100
      A All 400
      B 1 200
      B 2 300
      B 3 500
      B All 1000
      ;
      run;
      
      proc format;
      value $age_fmt '1','2' = '<18'
                      other   = '18+';
      run;
      
      proc sort data=have;
      by county;
      run;
      
      proc freq data=have (where=(agegrp ne 'All')) noprint;
      by county;
      table agegrp / out=want (drop=COUNT where=(agegrp in ('1','2')));
      format agegrp $age_fmt.;
      weight population;
      run;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-19
        • 1970-01-01
        • 2019-12-11
        • 1970-01-01
        • 2014-06-11
        相关资源
        最近更新 更多