user3658367
user3658367

Reputation: 641

arrays in sas with different dimensions

Beginning with a table,

A B C D E 
1 . 1 . 1
. . 1 . .
. 1 . 1 .

I am trying to get an output like this:

A B C D E     X Y Z
1 . 1 . 1     1 1 1
. . 1 . .     1 
. 1 . 1 .     1 1

Here is my code:

data want; 
set have; 

array GG(5) A-E; 
array BB(3) X Y Z;

do i=1 to 5;
do j=1 to 3;     
if gg(i)=1 then BB(j)=1; 
end; 
end; 
run;

I understand that the result that I get is wrong, as the dimensions of both the arrays are not co-operating. Is there another way to do this?

Upvotes: 0

Views: 104

Answers (3)

Longfish
Longfish

Reputation: 7602

My method is to copy the existing values to new variables X Y X temp1 temp2, then sort the values using call sortn, which will put the 1's and missing values together. Because call sortn only sorts in ascending order, with missing values coming first, I've reversed the variables in the array statement (creating them first in the correct order with a retain statement.

The unwanted variables temp1 and temp2 can then be dropped.

data have;
input A B C D E;
datalines;
1 . 1 . 1
. . 1 . .
. 1 . 1 .
;
run;

data want;
set have;
retain X Y Z .; /* create new variables in required order */
array GG{5} A--E;
array BB{5} temp1 temp2 Z Y X; /* array in reverse order due to ascending sort later on */
do i = 1 to dim(GG);
    BB{i} = GG{i};
end;
call sortn(of BB{*}); /* sort array (missing values come first, hence the reverse array order) */
drop temp: i; /* drop unwanted variables */
run;

Alternatively, here's a simpler solution as your criteria is pretty basic. As you're just dealing with 1's and missings, you can loop through the number of non-missing values in A-E and assign 1 to the new array.

data want;
set have;
array GG{5} A--E;
array BB{3} X Y Z;
do i = 1 to n(of GG{*});
    BB{i}=1;
end;
drop i; /* drop unwanted variable*/
run;

Upvotes: 0

stat
stat

Reputation: 669

why not something like this using a counter to identify which position is the actual non missing value?

data try;
   infile datalines delimiter=','; 
   input var1 var2 var3 var4 var5;
   datalines;                      
1,.,.,1,1,
.,1,.,.,.,
.,.,.,.,.,
.,1,.,1,.,
;
data want;
set try;
array vars[5] var1 var2 var3 var4 var5;
array newvars[5] nvar1 nvar2 nvar3 nvar4 nvar5;
do i=1 to 5;
if i=1 then count=0;
if vars[i] ne . then do;
count=count+1;
newvars[count]=vars[i];
end;
end;
drop i count var:;
run;

Upvotes: 0

Shenglin Chen
Shenglin Chen

Reputation: 4554

data want;
   set have;
   array v1 a--e;
   array v2 x y z;
   i=1;
   do over v1;
      if not missing(of v1) then do;
         v2(i)=v1;
         i+1;
      end;
   end;
   drop i;
run;

Upvotes: 2

Related Questions