Update/ Thanks to Bernd I could improve the function of how to import the data, so here’s the updated script! /Update

In R, you often may have scripts or code snippets that will be reused. In such cases, you can write functions for your every-day-tasks. For instance, importing and converting data is such a task. I have written a small function importSPSS.R to do this:

importSPSS <- function(path, enc=NA) {
  # init foreign package
  # import data as data frame
  data.spss <- read.spss(path, to.data.frame=TRUE, use.value.labels=FALSE, reencode=enc)
  # return data frame
getValueLabels <- function(dat) {
  a <- lapply(dat, FUN = getValLabels)
  return (a)
getValLabels <- function(x){
  rev(names(attr(x, "value.labels")))
getVariableLabels <- function(dat) {
  return(attr(dat, "variable.labels"))

This small function only gives little benefits regarding the saved typing effort. Referring to the code example under Migration, step 3: Importing (SPSS) variable and value labels, following things will change:

# Use "source" instead of "library"
# load data as data frame (function call)
myDat <- importSPSS("SPSS-dataset.sav")
# copy all variable labels in separated list
myDat_vars <- getVariableLabels(myDat)
# copy all value labels as separated list (function call)
myDat_labels <- getValueLabels(myDat)

The benefit especially lies in getting access to value labels. Instead of

hist(myDat[,86], main=myDat_vars[86], labels=rev(attr(myDat_labels[[86]], "names")), breaks=c(0:4), ylim=c(0,400), xlab=NULL, ylab=NULL)

we can now write

hist(myDat[,86], main=myDat_vars[86], labels=myDat_labels[[86]], breaks=c(0:4), ylim=c(0,400), xlab=NULL, ylab=NULL)

so we don’t need to call the attr-function nor remember to reverse the label order for plotting.