itzy
itzy

Reputation: 11765

Accumulate text variables in SAS across observations

This seems straightforward, but it's not working as expected:

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;

I would expect the result to have one observation containing

John|Jacob|Jingleheimer|Schmidt

but namelist is just John. What am I doing wrong?

Upvotes: 3

Views: 3593

Answers (3)

Chris J
Chris J

Reputation: 7769

Using the catx function allows you to specify the delimiter...

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

Upvotes: 0

Jay Corbett
Jay Corbett

Reputation: 28441

If you added STRIP to your assignment

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

it would work also

(but CATS is a really good solution)

Upvotes: 0

Robert Penridge
Robert Penridge

Reputation: 8513

You need to trim the whitespace before concatenating to your list.

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;

You could also use the cats() function (which does the trimming and concatenation for you):

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;

Upvotes: 5

Related Questions