-
-
Save superkeyor/0ac08c24f57b552ab647 to your computer and use it in GitHub Desktop.
Write an SPSS file from R with variable labels from the Hmisc package
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment