Skip to content

Instantly share code, notes, and snippets.

@kos59125
Last active December 26, 2015 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kos59125/7093510 to your computer and use it in GitHub Desktop.
Save kos59125/7093510 to your computer and use it in GitHub Desktop.
Saves R's data in a file and Loads data (*.data.R) into R. See http://blog.recyclebin.jp/archives/4052 (in Japanese/日本語) for details.
save_stan_data <- function(data, file, na.replace=NA) {
cat(file=file)
write <- function(...) {
cat(..., file=file, append=TRUE)
}
variables <- if (is.environment(data)) {
ls(envir=data)
} else {
names(data)
}
for (variableName in variables) {
value <- data[[variableName]]
for (attributeName in names(attributes(value))) {
if (attributeName != "dim") {
attr(value, attributeName) <- NULL
}
}
which.na <- is.na(value)
if (any(which.na)) {
alt <- if (is.list(na.replace)) {
na.replace[[variableName]]
} else {
na.replace
}
if (is.null(alt) || is.na(alt)) {
stop("NA found, but no alternative value is given")
}
value[which.na] <- alt
}
write(sprintf("%s <-", variableName), fill=TRUE)
write(deparse(value, control="showAttributes"), sep="\n")
}
}
load_stan_data <- function(name, file, envir=as.environment(-1L), parent=envir, type=c("list", "data.frame", "environment")) {
name <- deparse(substitute(name))
envir <- envir # forces evaluation
parent <- parent # same as above
type <- match.arg(type)
hash <- new.env(parent=parent)
sys.source(file, hash)
assign(name, switch(type, list=as.list(hash), data.frame=as.data.frame(as.list(hash)), environment=hash), envir=envir)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment