SAS Retain 不适用于 1 个字符串变量

SAS Retain not working for 1 string variable

当有超过 1 个记录具有相同的 urn 时,下面的代码似乎不适用于变量 all_s。 Var1、2、3 工作正常,但那个不行,我不明白为什么。我试图让 all_s 等于 single_var1,2,3 如果它是 first.urn 则没有空格连接但我希望它是

all_s = all_s + ',' + single_var1 + single_var2 + single_var3

当它不是那个骨灰盒的第一个实例时。

data dataset_2;
    set dataset_1;
    by URN;
    retain count var1 var2 var3 all_s;
    format var1 . var2 . var3 . all_s .;
    if first.urn then do;
        count=0;
        var1 = ' ';
        var2 = ' ';
        var3 = ' ';
        all_s = ' ';
    end;
    var1 = catx(',',var1,single_var1);
    var2 = catx(',',var2,single_var2);
    var3 = catx(',',var3,single_var3);

    all_s = cat(all_s,',',single_var1,single_var2,single_var3);

    count = count+1;
    if first.urn then do;
        all_s = cat(single_var1,single_var2,single_var3);
    end;
run;

一些示例数据会有所帮助,但我会试一试并请您尝试

all_s = cat(strip(All_s),',',single_var1,single_var2,single_var3);
如果组内 var1-var3 值的总长度超过 </code>,<p><code>all_s 不足以包含串联。 var1-var3</code>。</p> 似乎很可能出现这种情况 <p>我推荐使用<code>length函数来指定可变长度。 format 将创建一个特定长度的变量作为副作用。

catx 从串联中删除空白参数,因此如果您在有空白 single_varN 时想要串联中的空格,您将无法使用 catx

指定连接以便剥离非空白值且空白值是单个空白的要求可能不得不退回到旧学校trim(left(…方法

示例代码

data have;
  length group 8 v1-v3 ;
  input group (v1-v3) (&);
datalines;
1  111  222  333
1  .    444  555
1  .    .    666
1  .    .    .
1  777  888  999
2  .    .    .
2  .    b    c
2  x    .    z
run;

data want(keep=group vlist: all_list);
  length group 8 vlist1-vlist3  all_list ;
  length comma1-comma3 comma ;

  do until (last.group);
    set have;
    by group;

    vlist1 = trim(vlist1)||trim(comma1)||trim(left(v1));
    vlist2 = trim(vlist2)||trim(comma2)||trim(left(v2));
    vlist3 = trim(vlist3)||trim(comma3)||trim(left(v3));

    comma1 = ifc(missing(v1), ' ,', ',');
    comma2 = ifc(missing(v2), ' ,', ',');
    comma3 = ifc(missing(v3), ' ,', ',');

    all_list = 
      trim(all_list)
      || trim(comma)
      || trim(left(v1))
      || ','
      || trim(left(v2))
      || ','
      || trim(left(v3))
    ;

    comma = ifc(missing(v3),' ,',',');
  end;
run;

参考

SAS 具有用于字符串连接的运算符和多个函数

  • || 连接
  • cat 连接
  • catt 连接、修剪(删除尾随空格)每个参数
  • cats 连接、剥离(删除前导和尾随空格)每个参数
  • catx 连接,剥离每个参数并定界
  • catq 与定界符连接并引用包含定界符的参数

来自SAS 9.2 documentation

Comparisons

The results of the CAT, CATS, CATT, and CATX functions are usually equivalent to results that are produced by certain combinations of the concatenation operator (||) and the TRIM and LEFT functions. However, the default length for the CAT, CATS, CATT, and CATX functions is different from the length that is obtained when you use the concatenation operator. For more information, see Length of Returned Variable.

Note: In the case of variables that have missing values, the concatenation produces different results. See Concatenating Strings That Have Missing Values.