【问题标题】:SAS to R code First and last functionsSAS 到 R 代码第一个和最后一个函数
【发布时间】:2014-02-10 18:31:21
【问题描述】:

我对 SAS 比较陌生,正在努力将代码从 SAS 转换为 R。 我遇到了这个让我有点困惑的sn-p。

data A ; set B;
by date id Units;
retain Total;
if first.id and last.id then do;
Total=Units;
output; 
end;
else do ;
if  first.id then Total=Units;
else Total=sum(Total,Units);
if last.id then output;
end;
run;

如果我对这段代码的理解是正确的,这个 sn-p 会输出一个名为 A 的数据集,它是(在 SQL 术语中)所有第一次和最后一次出现的 id 和最后一次出现的 id 的并集。我对吗?那么 By 语句的目的是什么?我尝试通过 SAS 帮助,但我仍然感到困惑。

提前致谢!

【问题讨论】:

    标签: r sas output


    【解决方案1】:

    by 语句负责创建此操作所基于的 lastfirst 变量。没有它,您将无法访问这些变量。

    这段代码所做的是对变量求和,类似于

    proc sql;
    select id, sum(units) as total
    from b
    group by id;
    quit;
    

    基本上,如果您在单行(该 ID 为一行),Total=Units;否则,在第一行设置 total=units,然后对于每个额外的行,将单位添加到总数中,然后在该 ID 的最后一行,输出包含总数的行。

    【讨论】:

    • 谢谢!这有帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多