2012-10-03 71 views
3

这看起来非常简单,但预计它不工作:累加文本变量跨越观察

data names; 
    input name $12.; 
    cards; 
John 
Jacob 
Jingleheimer 
Schmidt 
; 
run; 

data names; 
    length namelist $100.; 
    set names end=eof; 
    retain namelist; 
    if _n_=1 then namelist=name; 
    else namelist = namelist || "|" || name; 
    if eof then output; 
run; 

我希望得到的结果有含

约翰一个观察|雅各布| Jingleheimer |施密特

但是namelist只是John。我究竟做错了什么?

回答

5

您需要在连接到列表之前修剪空白。

data names; 
    length namelist $100.; 
    set names end=eof; 
    retain namelist; 
    if _n_=1 then namelist=trim(name); 
    else namelist = trim(namelist) || "|" || trim(name); 
    if eof then output; 
run; 

您也可以使用猫()函数(为你做了微调和串联):

data names; 
    length namelist $100.; 
    set names end=eof; 
    retain namelist; 
    if _n_=1 then namelist=name; 
    else namelist = cats(namelist,"|",name); 
    if eof then output; 
run; 
+0

啊哈,谢谢!你能解释为什么吗?是否填充了导致填充可用空间的文本? – itzy

+2

当然 - 根据此链接(http://support.sas.com/documentation/cdl/en/basess/58133/HTML/default/viewer.htm#a001336080.htm)“当字符值小于长度它所属的变量,SAS用尾随空格填充该值。“如果您看到关于连接和删除内部空白的标题,它们会更详细一些。 –

0

如果添加脱至分配

strip(namelist) || "|" || name 

它会工作也

(但CATS是一个非常好的解决方案)

0

使用catx的功能允许您指定分隔符......

data names; 
    length namelist $100.; 
    set names end=eof; 
    retain namelist; 
    namelist = catx("|",namelist,name); 
    if eof then output; 
run;