Sas,为许多变量打印唯一值

时间:2017-01-11 19:20:09

标签: sql sas

如果我有这样的数据集A:

a b c
1 1 1
2 1 2
2 2 1
3 1 2
3 2 2

对于a和b列,我想在一个操作中打印唯一值(在我的真实数据集中,我有40列,我想打印唯一值。

我可以使用以下命令在sql中执行此操作:

proc sql;
create table test as
select distinct a from
A

但是我必须为每个变量运行它,这需要花费很多时间。我真的想打印出这种格式的唯一值:

a 1 2 3
b 1 2

甚至更好

a b
1 1
2 2
3 .

如果可以将所有变量名称和循环遍历每个变量名称并打印出唯一变量,我会非常高兴

这可能在SAS中。我不需要完整的解决方案。只是指向正确的方向。

3 个答案:

答案 0 :(得分:0)

我不知道这会节省时间,但您可以使用union all合并结果:

proc sql;
create table test as
    select distinct 'a', a from t union all
    select distinct 'b', b from t union all
    . . .;

答案 1 :(得分:0)

这很长但应该给出你想要的答案。它将您的变量放在一个列表中然后循环两次 - 第一次打印唯一值,第二次在合并后删除重复项:

data test;
    length a b c 3;
    input a b c;
    datalines;
    1 1 1
    2 1 2
    2 2 1
    3 1 2
    3 2 2
    ;
run;

** put variables into list **;
proc sql noprint;
    select NAME
    into: varlist separated by " "
    from dictionary.columns
    where upcase(libname)="WORK" and upcase(memname)="TEST";
quit;

** loop over each variable **;
%macro loop_through(varlist);
    %do i=1 %to %sysfunc(countw(&varlist.));;
        %let var=%scan(&varlist.,&i.);

        /* output the frequency for each variable only keeping the value */
        proc freq data = test noprint;
            table &var. / out=freq_&var.(keep=&var.);
        run;

        /* merge that output with the same dataset each iteration */
        data freq1_&var.; set freq_&var.;
            temp_var = "temp";
        run;

        data merged;
            merge freq1:;
            by temp_var;
        run;
    %end;

    /* remove duplicates after merging */
    %do i=1 %to %sysfunc(countw(&varlist.));;
        %let var=%scan(&varlist.,&i.);
        data merged; set merged;
            if lag(&var.) = &var. then &var. = .;
        run;
    %end;

    /* delete individual frequency datasets */
    proc datasets nolist; delete freq:; quit;

    /* output final dataset */
    data final; set merged;
        drop temp_var;
    run;
%mend;

%loop_through(&varlist.);

答案 2 :(得分:0)

在我看来,这会让你最接近。

data have;
input a b c;
datalines;
1 1 1
2 1 2
2 2 1
3 1 2
3 2 2
;;;;
run;
proc tabulate data=have out=want;
  class a b c;
  tables n,(a b c);
run;

然后转置或任何你喜欢的结果,以准确到达你想要的地方。