Arnold Cross
Arnold Cross

Reputation: 329

How can I make a connection object without an open connection in R?

I cannot seem to create a closed connection object. I want to have a connection object sitting around, so I can give it a connection if isOpen(myCon) returns FALSE. I would expect myCon<-file() to give me a closed connection, but isOpen(myCon) returns TRUE. I see from the help file that file() actually returns a connection to an "anonymous file", which is apparently just a memory location that acts like a file. ...not what I want. If I create the anonymous file and execute close(myCon), then isOpen(myCon) gives an invalid connection error rather than returning FALSE. I don't want to be trapping errors just to get my false value. How can I create a valid connection that's not open? There must be a way isOpen(myCon) can return FALSE, otherwise it's a somewhat pointless function. My OS is Windows 7.

Upvotes: 2

Views: 452

Answers (1)

Arnold Cross
Arnold Cross

Reputation: 329

file() works as long as the first parameter (description) is a non-empty string. Example:

> myCon <- file("dumdum")
> isOpen(myCon)
[1] FALSE

The key is that the second parameter (open) is left empty (the default). It does not matter whether the string used for description is an existing file or not. However, this does not mean that the connection can't be used. R opens the connection as needed. For example:

> myCon <- file("important log file.txt")
> isOpen(myCon)
[1] FALSE
> cat("Thinking this will fail, because the connection is closed.  ...wrong!", file=myCon)
> isOpen(myCon)
[1] FALSE

The file has just been overwritten with that one line.

The safe way to make a stand-by connection is to generate the description with tempfile(). That returns a string which is guaranteed "not to be currently in use" (...according to the help page. I interpret that to mean that the string is not the name of an existing file.)

> myCon <- file( tempfile() )
> isOpen(myCon)
[1] FALSE
> cat("Didn't mean to do this, but all it will do is create a new file.", file=myCon)
> isOpen(myCon)
[1] FALSE

In this case, that line was written to a file, but it did not overwrite anything.

Many thanks to Martin Morgan for pointing me in the right direction. I welcome additional comments.

Upvotes: 2

Related Questions