警告:关闭未使用的连接n

Eva*_*Eva 22 warnings r readline

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

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

Warning message:
closing unused connection 5 ("C:\\Commentary\\com.txt") 
Run Code Online (Sandbox Code Playgroud)

Rei*_*son 39

readLines()是一个功能,你不这样做close().您想要关闭该file()功能打开的连接.此外,你是return()荷兰国际集团之前关闭的任何连接.就函数而言,return()语句后面的行不存在.

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

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

但是,为了编写你的函数,我可能会采取略微不同的方法:

getCommentary <- function(filepath) {
    con <- file(filepath)
    on.exit(close(con))
    Commentary <-readLines(con)
    Commentary
}
Run Code Online (Sandbox Code Playgroud)

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

R> getCommentary("foo.txt")
[1] "foobar"
Run Code Online (Sandbox Code Playgroud)

我使用过on.exit(),一旦con创建,如果函数终止,无论出于何种原因,连接将被关闭.如果你把它留close(con)在最后一行之前的声明,例如:

    Commentary <-readLines(con)
    close(con)
    Commentary
}
Run Code Online (Sandbox Code Playgroud)

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

  • 或者只是不要使用文件.读取线与路径一起使用. (4认同)
  • @ hadley的评论是明智的(不出所料):更喜欢基础行为,这些行为构建良好,可以管理连接而不是自己处理它们.话虽如此,我投了上述答案,因为它是"on.exit"的插图,对于一般情况,这种明智的建议不适用. (4认同)