Last active
December 26, 2015 04:29
-
-
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.
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
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