DATA Step, Macro, Functions and more

Reversing with array

Reply
New User
Posts: 1

Reversing with array

Hi,

   I need to reverse every even number item in a questionnaire. How could I figure this out with an array statement?

 

Let's assume there are total 30 items but just even numbered items need to be reversed.

DATA sdqreversed;
set sdq;
T1SDQ2=9-T1SDQ2;
T1SDQ4=9-T1SDQ4;
T1SDQ6=9-T1SDQ6;
T1SDQ8=9-T1SDQ8;
T1SDQ10=9-T1SDQ10;
T1SDQ12=9-T1SDQ12;
T1SDQ14=9-T1SDQ14;
T1SDQ16=9-T1SDQ16;
T1SDQ18=9-T1SDQ18;
T1SDQ20=9-T1SDQ20;
T1SDQ22=9-T1SDQ22;
T1SDQ24=9-T1SDQ24;
T1SDQ26=9-T1SDQ26;
T1SDQ28=9-T1SDQ28;
T1SDQ29=9-T1SDQ29;
T1SDQ30=9-T1SDQ30;

run;

Super User
Posts: 17,819

Re: Reversing with array

You didn't declare an array, so you could start with that Smiley Happy

 

You can also use the VNAME function to get the name of the variable and then figure it if it's even or not to apply the transformation. 

Untested and sketched out below. You may want to verify the results from the numeric conversion and mod function. 

 

Also, you have 29 included in there, when it's not even.

 

 

data want;
set have;

array t1(30) t1sdq1-t1sd130;

do i=1 to dim(t1);
var_name = vname(t1(i));
var_name_number=input(substr(var_name, 6), 8.); 
if mod(var_name_number, 2) = 0 then do;
 t1(i)=9-t1(i);
end;
end;

run;

An alternative option is to only list the even variables in your array statement, but that's a manual process. Then you don't need the if condition or the vname function.

 

data want;
set have;

array t1(15) t1sdq2 t1sdq4 ... t1sdq30; *need to explicitly list them all out;

do i=1 to dim(t1);
   t1(i)=9-t1(i);
end;

run;
Respected Advisor
Posts: 4,646

Re: Reversing with array

Use an array and a loop with an increment of 2

 

data sdqreversed;
set sdq;
array T T1SDQ1-T1SDQ30;
do i = 2 to dim(T) by 2;
	T{i} = 9 - T{i};
	end;
drop i;
run;
PG
Ask a Question
Discussion stats
  • 2 replies
  • 198 views
  • 2 likes
  • 3 in conversation