Convenience function for writing Stan code to a (possibly temporary) file with a .stan extension.

write_stan_file(code, dir = tempdir(), basename = NULL)

Arguments

code

A single string containing a Stan program or a character vector containing the individual lines of a Stan program. See Examples.

dir

An optional path to the directory where the file will be written. If omitted, a temporary directory is used by default.

basename

If dir is specified, an optional string providing the basename for the file created. If not specified a file name is generated via base::tempfile().

Value

The path to the file.

Examples

# stan program as a single string stan_program <- " data { int<lower=0> N; int<lower=0,upper=1> y[N]; } parameters { real<lower=0,upper=1> theta; } model { y ~ bernoulli(theta); } " f <- write_stan_file(stan_program) print(f)
#> [1] "/var/folders/h6/14xy_35x4wd2tz542dn0qhtc0000gn/T//RtmpGraDrG/file2ed2636bec12.stan"
lines <- readLines(f) print(lines)
#> [1] "" "data {" #> [3] " int<lower=0> N;" " int<lower=0,upper=1> y[N];" #> [5] "}" "parameters {" #> [7] " real<lower=0,upper=1> theta;" "}" #> [9] "model {" " y ~ bernoulli(theta);" #> [11] "}" ""
cat(lines, sep = "\n")
#> #> data { #> int<lower=0> N; #> int<lower=0,upper=1> y[N]; #> } #> parameters { #> real<lower=0,upper=1> theta; #> } #> model { #> y ~ bernoulli(theta); #> } #>
# stan program as character vector of lines f2 <- write_stan_file(lines) identical(readLines(f), readLines(f2))
#> [1] TRUE