警告:关闭未使用的连接 n [英] Warning: closing unused connection n

查看:99
本文介绍了警告:关闭未使用的连接 n的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

getCommentary=function(){
    Commentary=readLines(file("C:\\Commentary\\com.txt"))
    return(Commentary)
    close(readLines)
    closeAllConnections()
}

我不知道这个功能有什么问题.当我在 R 中运行它时,它不断给我以下警告:

I have no idea what is wrong with this function. When I run this in R, it keeps giving me the following warning:

Warning message:
closing unused connection 5 ("C:\\Commentary\\com.txt") 

推荐答案

readLines() 是一个函数,你不用 close() 它.您想关闭由 file() 函数打开的连接.此外,您在关闭任何连接之前return().就函数而言,return() 语句之后的行不存在.

readLines() is a function, you don't close() it. You want to close the connection opened by the file() function. Also, you are return()ing before you close any connections. As far as the function is concerned, the lines after the return() statement don't exist.

一种选择是保存由 file() 调用返回的对象,因为您不应该只关闭函数打开的所有连接.这是一个非函数版本来说明这个想法:

One option is to save the object returned by the file() call, as you shouldn't be closing all connections only those your function opens. Here is a non-function version to illustrate the idea:

R> cat("foobar\n", file = "foo.txt")
R> con <- file("foo.txt")
R> out <- readLines(con)
R> out
[1] "foobar"
R> close(con)

然而,为了编写您的函数,我可能会采取稍微不同的策略:

To write your function, however, I would probably take a slightly different tack:

getCommentary <- function(filepath) {
    con <- file(filepath)
    on.exit(close(con))
    Commentary <-readLines(con)
    Commentary
}

使用如下,上面创建的文本文件作为示例文件读取

Which is used as follows, with the text file created above as an example file to read from

R> getCommentary("foo.txt")
[1] "foobar"

我使用了 on.exit() 这样一旦 con 被创建,如果函数终止,无论什么原因,连接都将关闭.如果你把它留在最后一行之前的 close(con) 语句中,例如:

I used on.exit() so that once con is created, if the function terminates, for whatever reason, the connection will be closed. If you left this just to a close(con) statement just before the last line, e.g.:

    Commentary <-readLines(con)
    close(con)
    Commentary
}

该函数可能会在 readLines() 调用时失败并终止,因此连接不会被关闭.on.exit() 会安排关闭连接,即使函数提前终止.

the function could fail on the readLines() call and terminate, so the connection would not be closed. on.exit() would arrange for the connection to be closed, even if the function terminates early.

这篇关于警告:关闭未使用的连接 n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆