Created
April 21, 2012 19:10
-
-
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
This file contains 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
require(devtools)
source_url("https://raw.github.com/gist/2439148/038c8ea5d6f7bb22055380fb34675c0f8787b5b6/write.Hmisc.SPSS.R")