crayfishcray
crayfishcray

Reputation: 409

Dynamically set size of array without hardcoding

So I have datasets with variables and values like so:

A1 A2 A3 A4 A5 A6
1  3  5  6  10 2

The variables can go up to A2000 in certain cases. I want to perform the same operation on each variable using an array. Is there a way to dynamically set the size of the array without manually typing it?

Example code of what I am striving for is below

data A;
input A1-A6;
datalines;
1 3 5 6 10 2;
run;

data A;
set A;
array a[*] a1-a&size;
do i=1 to &size;
{perform some operation here}
end;
run;

My question is how can I write code to get the parameter &size that represents the size of the array? In this example, &size = six.

Upvotes: 2

Views: 714

Answers (1)

Joe
Joe

Reputation: 63424

Sure, use the : wildcard. This only works if a1-a6 are already defined (or a-whatever) in the dataset, though.

data have;
  input a1-a6;
datalines;
1 2 3 4 5 6
7 8 9 10 11 12
;;;;
run;

data want;
  set have;
  array a a:;
  do i=1 to dim(a);
    sum = sum(sum ,a[i]);
  end;
run;

Otherwise, what you put above would absolutely work. You don't need the [*] bit, though, and I prefer to keep the dim instead of &size on the loop control in case you change the way this works in the future. Of course you need to have a way to determine &size which will depend on your data.

%let size=6;
data want;
  set have;
  array a a1-a&size.;
  do i=1 to dim(a);
    sum = sum(sum ,a[i]);
  end;
run;

Upvotes: 1

Related Questions