Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create text connection from string variable?

Tags:

r

This should be quick to answer:

I want to use jags packages' jags.model function. Among many arguments it needs the argument file:

file - the name of the file containing a description of the model in the JAGS dialect of the BUGS language.

Alternatively, file can be a readable text-mode connection, or a complete URL.

I want to pass string to this argument. One way to walk-around this problem is to write the string into temporary file and pass the file name. But I hope there is a straightforward way to convert string into connection.

like image 651
Adam Ryczkowski Avatar asked Feb 20 '13 11:02

Adam Ryczkowski


2 Answers

You can use textConnection like this (here with the read.csv function, but I guess jags.model should work the same way) :

mytext <- "x,y\n1,2\n3,4"
read.csv(textConnection(mytext))
#   x y
# 1 1 2
# 2 3 4
like image 88
juba Avatar answered Oct 30 '22 20:10

juba


I would just add a small point about textConnection. I have occasionally ran into problems when I used jags.model(textConnection(x)...) inside a large for loop (i.e., more than 125 iterations or so). Essentially, it seems that the textConnections were being opened, but not closed, and then I would receive an error eventually after too may textConnections had been opened stating that all connections are in use.

I'm not entirely sure of the best solution, but I assume you could do something like:

zz <- textConnection(x)
jags.model(zz, ...)
close(zz)
like image 1
Jeromy Anglim Avatar answered Oct 30 '22 19:10

Jeromy Anglim