SAS 从行中检索值

SAS retrieving values from row

我想从 SAS table - 中检索行级值(与帐号关联的贷款) 请查看以下示例。

输入

Account Number  Loans
123             abc, def, ghi
456             jkl, mnopqr, stuv
789             w, xyz

输出

Account Numbers Loans
123             abc
123             def
123             ghi
456             jkl
456             mnopqr
456             stuv
789             w
789             xyz

外借以逗号分隔,没有固定长度。

使用 countw() 计算一行中值的数量,并使用 scan() 挑选它们。

两者都有最后一个可选变量来指定分隔符,在您的例子中是 ,

data Loans (keep= AccountNo Loan);
    infile datalines truncover;
    Input @1 AccountNo 3. @17 LoanList 0.;
    if length(LoanList) gt 240 then put 'WARNING: You might need to extend Loans';

    label AccountNo = 'Account Number' Loan = 'Loans';
    do loanNo = 1 to countw(LoanList, ',');
        Loan = scan(LoanList, loanNo, ',');
        output;
    end;
    datalines;
123             abc, def, ghi
456             jkl, mnopqr, stuv
789             w, xyz
;

proc print data=Loans label noobs;
run;

反向操作需要不同的技术。

要启用 by AccountNo 处理,我们必须首先从输入构建一个 SAS 数据集,然后使用 set 语句将其读回。

data Loans;
    infile datalines;
    input @1 AccountNo 3. @5 Loan .;
    datalines;
123 15-abc 
123 15-def 
123 15-ghi 
456 99-jkl 
456 99-mnopqr 
456 99-stuv 
789 77-w 
789 77-xyz
;
data LoanLists;
    set Loans;
    by AccountNo;

现在创建足够长的 Loanlist 并覆盖 SAS 的默认行为以重新初始化每个观察的所有变量(=数据行)。

    format Loanlist 0.;
    retain Loanlist;

收集一个账户的所有贷款,用逗号和空格分隔。

    if first.AccountNo then Loanlist = Loan;
    else Loanlist = catx(', ',Loanlist,Loan);
    if length(LoanList) gt 240 then put 'WARNING: you might need to extend LoanList';

每个帐户仅保留完整列表。

    if last.AccountNo;
    drop Loan;
proc print;
run;