Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

  • Is there a way to write and access a pseudo-file that only exists in memory?
  • where is the feature documented?
    ?connections appears to be a good lead, but it is not clear to me how to use the information provided

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

  • What are the primary uses of such a feature beyond what I described above?
  • Are situations in which this feature should not be used?
like image 832
David LeBauer Avatar asked Dec 26 '22 16:12

David LeBauer


1 Answers

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>"
like image 187
Josh O'Brien Avatar answered Jan 08 '23 21:01

Josh O'Brien