首页 > 解决方案 > SAS: divide table by another table

问题描述

I am pretty new is SAS and now i am struggling with division table by table. Tables have the same size. My goal is to divide each element of table_1 by the corresponding element of table_2, producing a new table. Google advises to use SAS/IML but i have no access to it. Is there any option to do that in data step? Another ideas?

For instance first table looks like:

    30 30
    30 30

Second table:

    2 3
    5 6

Then output table should be:

    15 10
    6   5

Thank you a lot in advice!

标签: sas

解决方案


一种方法是将两个表合并在一起并执行除法。

data dividend;
  a = 30; b = 30; output;
  a = 30; b = 30; output;
run;

data divisor;
  c = 2; d = 3; output;
  c = 5 ; d = 6 ; output;
run;

data comb;
  merge dividend divisor;

  q1 = a/c;
  q2 = b/d;

  keep q1 q2;
run;

这假设在被除数和除数行之间存在 1 对 1 的对应关系

编辑以回应评论中的问题

假设您有 2015 年到 2010 年,每个有 4 个季度,您可以编写一个宏循环:


%macro divide;

%let years = %str(2015 2016 2017 2018 2019);
%let qtrs = %str(Q1 Q2 Q3 Q4);

data comb;
  merge dividend divisor;

  %let i = 1;
  %do %while (%scan(&years, &i) ne );

    %let year = %scan(&years, &i);
    %let j = 1;

    %do %while (%scan(&qtrs, &j) ne );
       %let q = %scan(&qtrs, &j);
       R_&q._&year = &q._&year._D / &q._&year._A;
       %let j = %eval(&j + 1);
    %end;

    %let i = %eval(&i + 1);
  %end;

  keep R_:;

run;

%mend;

%divide;


推荐阅读