B K
B K

Reputation: 59

Can I use array based processing to add additional column(s)? SAS

I have a dataset (a) that looks like this:

Name                     Value
Cost_1                     28
Cost_2                     22
Unit_1                     Fixed
Unit_2                     C

Is it possible to use an array to have a dataset that looks like this:

Name                           Cat_1           Cat_2
Cost                             28              22
Unit                            Fixed             C


%let Cat_Count = 2;
data b;
set a;

array category [&Cat_Count] cat_1-cat_&Cat_count;
.
.
.
run;

Not sure how to execute this...the macro variable cat_count will be dynamic.

Upvotes: 0

Views: 231

Answers (1)

Reeza
Reeza

Reputation: 21264

You can use array's but a transpose is more efficient. First create a new column that separates name into the name and count and then use a proc transpose.

data have;
input Name $                    Value $;
cards;
Cost_1                     28
Cost_2                     22
Unit_1                     Fixed
Unit_2                     C
;;;;

run;

data have_cat;
set have;
cat = input(scan(name, 2, "_"), 8.); *numeric conversion not required for this approach but for array approach;
name = scan(name, 1, "_");
run;

proc sort data=have_cat;
by name cat value;
run;

proc transpose data=have_cat out=want prefix=cat_;
by name;
id cat;
var value;
run;

Array method - requires everything before PROC TRANSPOSE and max_count macro variable.

%let Cat_Count = 2;
data want_array;
set have_cat;
by name;
array category(&cat_count) $ cat_1-cat_&cat_count;
retain cat_1-cat_&cat_count;

if first.name then 
call missing(of category (*));

category(cat) = value;

if last.name then output;
run;

Upvotes: 1

Related Questions