Showing posts with label Array. Show all posts
Showing posts with label Array. Show all posts

Saturday, April 9, 2016

SAS Arrays

SAS Arrays : Introduction

It provides a simple, appropriate way to process a group of variables in a SAS DATA step.

Syntax
Array array-name {number-of-elements} list-of-variables;
Note: You can use [ ] or { } or ( ) for defining number of elements in the ARRAY statement.

Examples

1.  ARRAY ABC[5] a b c d e; 

In the example above, ABC is an array-name, 5 implies the number of variables in array and "a b c d e" are the fields that make up the array.

2. ARRAY ABC[*] a b c d e; 

In the example above, SAS would automatically calculate the number of variables in array.

3. ARRAY ABC[*] X1-X10;

Where the X1 variable contains the X1 value, X2 contains the X2 value, etc.

4. ARRAY ABC[*]  $ X1-X10;

If the variables are of character type then use $ sign before specifying list of variables.

Sample Data

SAS Array : Example
data temp;
input x1 x2 x3 x4$ x5$;
cards;
1 2 3 AA BB
2 3 4 AB CC
3 4 5 AC DD
4 5 6 AD EE
5 6 7 AE FF
6 7 8 AF GG
;
run;
Example I : Numeric variables having value greater than 3 need to be replaced with missing value

data test;
set temp;
array nvars {3} x1-x3;
do i = 1 to 3;
if nvars{i} > 3 then nvars{i} =.;
end;
run;  
Output : Array Statement
Why i is 4 in the output data set?

The first time the loop processes, the value of count is 1; the second time, 2; and the third time, 3. At the beginning of the fourth iteration, the value of count is 4, which is found to be greater than the stop value of 3 so the loop stops. However, the value of i is now 4 and not 3, the last value before it would be greater than 3 as the stop value.
Note : We can drop variable "i" with drop statement or drop data set option.
Improvised version of the above code 
data test;
set temp;
array nvars (*) _numeric_;
do i = 1 to dim(nvars);
if nvars{i} > 3 then nvars{i} =.;
end;
drop i;
run;
Notes - 
  1. The "_numeric_" is used to specify all the numeric variables.
  2. The DIM function returns the number of elements (variables).

Example II. : Extract first letter of all the character variables
data test;
set temp;
array cvars (*) _character_;
do i = 1 to dim(cvars);
cvars{i} = substr(cvars{i},1,1);
end;
drop i;
run;
 Note - The "_character_" is used to specify all the character variables.

Example III. : Extract first letter and fill in the new character variables
data test;
set temp;
array cvars (*) _character_;
array dvars (*) $ x6 X7;
do i = 1 to dim(cvars);
dvars{i} = substr(cvars{i},1,1) ;
end;
drop i;
run;
Example IV : Assign Initial Values in a SAS Array
data abcd;
set temp;
array nvars (*) _numeric_;
array pvars (*) px1 px2 px3;
array pctinc {3} _temporary_ (1.1 , 1.2 ,1.3); do i = 1 to dim(nvars);
pvars{i} = nvars{i} * pctinc{i};
end;
drop i;
run;  
Notes -
  1. In the above example, we are multiplying variables' values with different numbers.
  2. When the key word _TEMPORARY_ is used in a ARRAY statement, data elements are created but are not stored in the data file.

Example V : Calculate Percentage Growth
data abcd;
set temp;
array nvars(*) _numeric_;
array diff{2} _temporary_;
array percent{2};
do i = 1 to 2;
diff{i} = nvars{i +1} - nvars{i};
percent{i} = diff{i} / nvars{i} ;
end;
drop i;
run;

Using the OF Operator in a SAS Array

Examples :

array gnp (*) x y z;

The following two statements are equivalent.
sumgnp = sum(of gnp(*)) ;
sumgnp = sum(x,y,z); 
*Calculate the mean;
  mean_score = mean(of gnp(*));

* Calculate the minimum;
   min_score = min(of gnp(*));

DO OVER LOOP

The DO OVER loop is one of the most useful DO loops. It can be used with an array when indexing of the array is not needed.
data test;
set temp;
array nvars _numeric_;
do over nvars;
if nvars > 3 then nvars = .;
end;
run;
                     
     SOURCE                          


Tuesday, April 5, 2016

Arrays in SAS


You must have seen arrays being used in various programming languages and must already know quite a bit about them, but before we go into the details let me tell you one thing : 

ARRAYS IN SAS ARE DIFFERENT FROM ANY OTHER LANGUAGE..!!

In most of the languages array is a data structure, holding data values, but in SAS it is not a data structure, it is just a collective name given to a group of variables. Being clear with this distinction is very integral to the part of using arrays successfully in SAS.

In SAS the most important function of the array is to reduce the lines of code where a programs involves repetitive calculations on different variables. I have seen most programmers shy away from their use, but let me tell you that it is a wonderful tool to make your code simple. Also in some instances arrays provide flexibility to make your code dynamic, I’ll get back to this later.

So let us get down to the dirty details :



What are arrays?

An Array is a grouping of variables of the same type used to perform repetitive operations on those variables.

Syntax:

Array array_name[dimension] $ length variable-list

Array – The ARRAY keyword for decleration

Array_name – Any valid SAS name (Do not use function names)

Dimension – Number of elements in the array(If unknown can use * but then we have to provide the varable list)

$ - Tells that the array is character array.

Length – Length of each variable

Variable list – List of variables to be part of the array(Can use named ranges)

Usage:

We have a dataset with 10 variables(kg1 to kg10) containing weights of a patients measure for 10 consecutive weeks. We want to convert these weight to pounds. One way we can do it is :

data kg_to_lbs;
      set weights;
      lbs1=kg1*2.2;
      lbs2=kg2*2.2;
      lbs3=kg3*2.2;
      ...
      lbs10=kg10*2.2;
run;

But this generates 13 lines of code for one simple calculation. Imagine when we have 100 such measurements, So here we can use arrays to make code shorter and easy to understand:

data kg_to_lbs;
      set weights;
      array kg_array {10} kg1-kg10;
      array lbs_array {10} lbs1-lbs10;
      do i = 1 to 10;
            lbs_array{i} = (kg_array{i})*2.2;
      end;
run;

cool na..and there is nothing complicated about this, you just need to declare an array and use a simple do loop.

Below are a few points about arrays which will be all you need to know about them to utilize arrays to their full potential.

Important points to note about arrays:

1 Variables used in an array must be of the same type. Either all numeric or all character.

2  Variables need not be preexisting variables, if they does not exist then SAS creates them for you. This converts into a useful application of creating variables through arrays.

3  SAS needs to know the size(number of elements) of the array while you are creating it. You can supply the size  in brackets next to the array name 

Array test[10] $5; 
Any array of 10 elements

Or you can let SAS count them for you using the number of variables in the variable list.

Array test1[*] $ var1 – var5

You cannot emit both the dimension and variable list together.

4)  Array does not accept numeric variables in the brackets whose value may define the dimension because it creates the array in compile time and the value of the variable used in brackets will be available only in compile time.

Array test[num_var];
ERROR : Array requires a numeric constant

5)  If we want to use all numeric or all character variables of a dataset without bothering about their names then you can declare the array like :

Array nums[*] _NUMERIC_;
Array nums[*] _CHARACTER_;

6)  Sometimes we need an array to hold values temporarily but do not want to output those variables to the final dataset then we can use temporary arrays. They are declare as :

Array arr_name[10] _TEMPORARY_;

Functions used with arrays :

DIM FUNCTION :

This function helps to determine the number of  elements in a array dynamically so while looping you do not have to hardcode it.
For e.g.

Do i=1 to 10;
A[i]= b[i] + c[i]
End;

Can also be written as :

Do i=1 to dim(a);
A[i]= b[i] + c[i]
End;

VNAME FUNCTION :

We get the values of variables in an array using the array name and subscript but if we want the name of the element(variable) by its subscript then we can use the vname function. For e.g.

array arr_name[*] X Y Z P Q R;
i=3;
vars = Vname(arr_name [i]); 

So vars will be initialized to the name of the third variable in the list which is Z.

OF OPERATOR :

This operator is very useful when we have to perform and operation on all elements(or variables) of an array. For e.g
We need a sum of all elements of an array we can write :
X=sum(a[1],a[2],a[3],a[4],a[5],a[6],a[7]…)

But if we don’t know how many elements are there or it changes every time then you need to update it again and again, so instead we can write

X=sum(of a[*]);

Cool and easy.. :-)