Dick Duck's SAS tips

This is the nest where I keep my SAS eggs. It's all here... Arrays, control loops, links to online SAS resources, you name it.

Thursday, February 23, 2006

Recoding answer files

Say you have a file with responses to a test that is a mixture of multiple choice (answers coded as single characters, A through F) and open-ended questions, scoring either 0 or 1 (a numeric variable of a wasteful length 8). So you can treat all the data the same way, you want to convert all the variables to numerics of length 3. We use a variation on the old char to num conversion (and the variables turn up in the right order if they weren't before to boot).

data s1b (drop=n1-n35 i);
set s1a (rename=(q1-q35=n1-n35));

length q1-q35 3.;

/* convert char to num of length 3 */
array qc $ n1-n4 n6 n8-n9 n11-n18 n20 n23 n25-n35;
array qn q1-q4 q6 q8-q9 q11-q18 q20 q23 q25-q35;

do i = 1 to dim(qc);
select (qc[i]);
when ('') qn[i] = 9;
when ('A') qn[i] = 2;
when ('B') qn[i] = 3;
when ('C') qn[i] = 4;
when ('D') qn[i] = 5;
when ('E') qn[i] = 6;
when ('F') qn[i] = 7;
/* 8 = error flag */
otherwise qn[i] = 8;
end;
end;

/* convert num of length 8 to length 3 */
array qn8 n5 n7 n10 n19 n21 n22 n24;
array qn3 q5 q7 q10 q19 q21 q22 q24;
do i = 1 to dim(qn8);
qn3[i] = qn8[i];
end;
run;

1 Comments:

Anonymous Anonymous said...

thank you!
this code is VERY USEFUL!

4:02 pm  

Post a Comment

<< Home