kmm - 1 year ago 50
R Question

# How can I split a string into an alist() in R?

I'm using the package

, which has a functions
`map()`
and
`map2stan()`
to carry out Bayesian estimation (the latter as an interface to
`rstan`
).
`map()`
and
`map2stan()`
take an
`alist()`
of formulas to define the likelihood and priors, such as:

``````alist(
height ~ dnorm(mu, sigma),
mu ~ dnorm(178, 20),
sigma ~ dunif(0, 50)
)
``````

which prints as:

``````[[1]]
height ~ dnorm(mu, sigma)

[[2]]
mu ~ dnorm(178, 20)

[[3]]
sigma ~ dunif(0, 50)
``````

I'm trying to explore the effects of priors, so I want to be able to pass different sets of means and standard deviations. I can get the priors into a semicolon separated string like:

``````s <- "height ~ dnorm(mu, sigma); mu ~ dnorm(178, 20); sigma ~ dunif(0, 50)"
``````

from which I think I should be able to split on
`;`
and assign to an
`alist()`
. But I can't figure out this last step.

I have tried variations of:

``````do.call("alist", unlist(strsplit(s,";")))
``````

and

``````as.vector(unlist(strsplit(s,";")), mode = "alist")
``````

The former fails with
`second argument must be a list`
and the latter because
`as.vector()`
doesn't have an "alist" mode.

Maybe the more general question is: how can I get a string into an
`alist()`
? I have read the answer in this question, but I can't figure out how to adapt it for this particular problem.

``````lapply(strsplit(s, ";")[[1]], function(x) parse(text = x)[[1]])