Rich Scriven
Rich Scriven

Reputation: 99331

Remove connection object immediately after closing connection

This is a two-part question regarding the following chunk of code.

> ## ran rm(list = ls()) prior to the following
> closeAllConnections()
> tc <- textConnection("messages", "w")
> isOpen(tc)
# [1] TRUE
> close(tc)
> ls()
# [1] "messages" "tc" 
> is.object(tc)
# [1] TRUE     
> class(tc)
# [1] "textConnection" "connection"      
> tc
# Error in summary.connection(x) : invalid connection
  1. Why isn't tc removed from the list of objects, ls(), immediately when the tc connection is closed, and what does invalid connection mean? Is there a reason why R keeps tc in the list?

  2. Is there a way to remove it from the object list immediately after it's closed? I really don't want to call rm() if it's not necessary. Perhaps I missed an argument somewhere while scanning the help files.

The reason this is important is because I have a function called list.objects that returns an error after I run the above code, but does not otherwise (possibly because tc has two classes).

Upvotes: 1

Views: 1182

Answers (2)

BrodieG
BrodieG

Reputation: 52637

For 1., tc isn't removed from the list of objects because close doesn't delete the variable you use to contain the pointer to the connection. Rather, close closes the pointer and effectively removes it from the open file connections list (see showConnections). The variable that contains the pointer still exists, it's just that the pointer points nowhere. This explains why you get an error when you type tc after you close it, you're trying to look at a file connection that goes nowhere.

For 2., what's so hard about close(tc); rm(tc)? Hardly any more typing than if there actually was a "delete my first argument" parameter.

Upvotes: 1

merlin2011
merlin2011

Reputation: 75555

tc is a variable that holds a reference to certain state. There is no particular reason that a call to close() should come with an rm() built-in. That would be like expecting a TV remote to disappear on its own after you turn off the TV by hitting the power button.

I think you will have to call rm(tc) to remove it.

Upvotes: 1

Related Questions