BookmarkSubscribeRSS Feed
mike44
Calcite | Level 5

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;

2 REPLIES 2
Reeza
Super User

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

 

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;
PGStats
Opal | Level 21

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

sas-innovate-2024.png

Today is the last day to save with the early bird rate! Register today for just $695 - $100 off the standard rate.

 

Plus, pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.

 

Register now!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 2 replies
  • 1647 views
  • 2 likes
  • 3 in conversation