How to extract codes from a factor

First of all, I would like to apologize for the fact that in my question I will not be very clear. I am completely unfamiliar with R, and my terminology will not be so good.

We get the SPSS file from an external company that contains the survey data. We have an R script to extract the data and write it to a CSV file. It works great.

The second part of the script will build an INI-style file for all possible participants. As an example, for AGE we will have something like

[ AGE ]
1 = Under 13
2 = 13 - 15
3 = 15 - 25
4 = 25+

The CSV file will have one of 1, 2, 3, or 4 for each line. Until recently, all possible answers were numbered starting with 1, but now some of them start with 0. Therefore, we would like to have something like:

[ AGE ]
0 = Under 13
1 = 13 - 15
2 = 15 - 25
3 = 25+

Below is the current R code we are using. I know where this is going wrong, but I do not know how to fix it.

data<-read.spss(inputFile, to.data.frame=TRUE);
fileOut<- file(valuesExportFile, "w");
for (name in names(data)) {
  cat("[", name,"]\n", file=fileOut);
  variableValues<-levels(data[[name]]);
  numberOfValues<-nlevels(data[[name]]);
  if (numberOfValues > 0) {
     for (i in 1:numberOfValues) {
         cat(i, '= "', variableValues[i], '"', "\n", file=fileOut);
     }
  }
};
close(fileOut);

. perl script, spssread.pl, , , - , , . script, , R, , , script.

, ?

+3
1

, , .

, use.value.labels=FALSE, value.labels. , , .

data<-read.spss(inputFile, to.data.frame=TRUE, use.value.labels=FALSE);
fileOut<- file(valuesExportFile, "w");
for (name in names(data)) {
    cat("[", name,"]\n", file=fileOut);
    variables<-attr(unclass(data[[name]]), "value.labels");
    for (label in names(variables)) {
        cat(variables[[label]], '= "', label, '"', "\n", file=fileOut);
    }
};
close(fileOut);

[ AGE ]
8 = " 65+ "
7 = " 55 to 64 "
6 = " 45 to 54 "
5 = " 35 to 44 "
4 = " 25 to 34 "
3 = " 21 to 24 "
2 = " 16 to 20 "
1 = " 13 to 15 "
0 = " Under 13 "

, . - , ,

[ AGE ]
0 = " Under 13 "
1 = " 13 to 15 "
2 = " 16 to 20 "
3 = " 21 to 24 "
4 = " 25 to 34 "
5 = " 35 to 44 "
6 = " 45 to 54 "
7 = " 55 to 64 "
8 = " 65+ "

EDIT: 04/05/12

(. )

data<-read.spss(inputFile, to.data.frame=TRUE, use.value.labels=FALSE);
fileOut<- file(valuesExportFile, "w");
for (name in names(data)) {
    cat("[", name,"]\n", file=fileOut);
    variables<-attr(unclass(data[[name]]), "value.labels");
    variables<-variables[order(as.numeric(variables))];
    for (label in names(variables)) {
        cat(variables[[label]], '= "', label, '"', "\n", file=fileOut);
    }
};
close(fileOut);
+2

All Articles