0
votes

I have a data set consists of 60 variables and 100 observations. The observations for each question can take one of the following characters (a, b, c, d, e). I want to convert them to numeric, so I tried to use Do loop, but for some reason, it didn't run. Here is my SAS code:

DATA nXYZ;
set data XYZ;

array nQ {60} Q1-Q60;
do i = 1 to 60;

if Q[i] = 'a' then nQ[i] = 5;
else if Q[i] = 'b' then nQ[i] = 4;
else if Q[i] = 'c' then nQ[i] = 3;
else if Q[i] = 'd' then nQ[i] = 2;
else if Q[i] = 'e' then nQ[i] = 1;
end;

RUN;

I was wondering what things I did wrong. Your help is appreciated.

1
You forgot to create the Q array. - mvherweg
You might want to look into proc format. It exists to address this sort of task. - Jeff

1 Answers

0
votes

You cannot change a character variable to a numeric variable, per se, without using another variable name. You could say Q[i]='5' (assuming you properly defined your arrays) but you could not get Q[i] to store 5 as a number that you could then do math to. If you did get that code working by adding the additional array reference, it would work, but it would assign '5' not 5.

The workaround is to rename the variables and convert the renamed variable back into the proper variable name. That's a bit sticky when you have 60 of them, but it's possible.

The basic concept:

data nXYZ;
set xyz(rename=(Q1=cQ1 Q2=cQ2));
array cQs cq1-cq2;
array nQs q1-q2;
do _t = 1 to dim(nQs);
  nQs[_t] = 6-(rank(cQs)-96); *'a' = 97 .. 'z' = 122;
end;
run;

You can construct that rename list programmatically.