David LeBauer
David LeBauer

Reputation: 31741

Can I write to and access a file in memory in R?

I am writing tests for an R function that imports an xml file, settings.xml.

Currently, when I write a test for functions that depend on the contents of foo.xml, including the function read.settings in the following example:

writeLines("<fee><fi><\fi>\fee>", con = "/tmp/foo.xml")
settings <- read.settings("/tmp/foo.xml")
file.remove("/tmp/foo.xml")

But a number of issues have come up related to making the test system-independent. For example, /tmp/ may not be writeable or an error in read.settings() leaves an orphaned file in the test directory, etc. This is a trivial example and I can think of ways around these issues, but I recall such a solution in an answer to a previous question, which I now can not find, in which the con is not a file but an object in memory. I am sure that there are many situations in which it would be useful not to actually write a file.

As follow up (but not to be too open-ended)

Upvotes: 4

Views: 2319

Answers (2)

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162321

Here's a construct that might be helpful. tempfile() returns a valid name for a temporary file on any operating system, and the call to on.exit(unlink()) ensures that the temporary file gets removed, no matter what else happens.

test1 <- function() {
    temp <- tempfile()
    on.exit(unlink(temp))
    writeLines("<fee><fi><\fi>\fee>", con = temp)
    settings <- readLines(temp)
    settings
}

test1()
# [1] "<fee><fi><\fi>\fee>"

Upvotes: 7

Matthew Plourde
Matthew Plourde

Reputation: 44614

You can turn any string into a connection with textConnection.

xml.txt <- '<fee><fi><\fi>\fee>'
con <- textConnection(xml.txt)
settings <- read.settings(con)

I find string connections useful in situations where the connection functions are handy for what you're doing, but the tasks involved will result in a file on disk sitting open for an extended period. You can use the text connection as buffer.

Note, you can't use seek to reset the position of a text connection after reading its contents the way you can with file connections.

Upvotes: 4

Related Questions