Skip to content

Instantly share code, notes, and snippets.

@mrdwab
Created April 21, 2012 19:10
Show Gist options
  • Save mrdwab/2439148 to your computer and use it in GitHub Desktop.
Save mrdwab/2439148 to your computer and use it in GitHub Desktop.
Write an SPSS file from R with variable labels from the Hmisc package
write.Hmisc.SPSS = function(data, datafile, codefile) {
# EXAMPLE DATA (see: http://stackoverflow.com/q/10181730/1270695)
# df <- data.frame(id = c(1:6),
# p.code = c(1, 5, 4, NA, 0, 5),
# p.label = c('Optometrists', 'Nurses',
# 'Financial analysts', '<NA>',
# '0', 'Nurses'),
# foo = LETTERS[1:6])
# Add some variable labels using label from the Hmisc package
# require(Hmisc)
# label(df) <- "Sweet sweet data"
# label(df$id) <- "id !@#$%^"
# label(df$p.label) <- "Profession with human readable information"
# label(df$p.code) <- "Profession code"
# label(df$foo) <- "Variable label for variable x.var"
#
# USAGE
# write.Hmisc.SPSS(df, datafile="df.sav", codefile="df.sps")
#
# Original "write.SPSS" function taken from:
# https://stat.ethz.ch/pipermail/r-help/2006-January/085941.html
a = do.call(llist, data)
tempout = vector("list", length(a))
for (i in 1:length(a)) {
tempout[[i]] = label(a[[i]])
}
b = unlist(tempout)
label.temp = structure(c(b), .Names = names(data))
attributes(data)$variable.labels = label.temp
source("http://dl.dropbox.com/u/2556524/R%20Functions/writeSPSS.R")
write.SPSS(data, datafile, codefile)
}
@mrdwab
Copy link
Author

mrdwab commented Apr 21, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment