getCommentary=function(){
Commentary=readLines(file("C:\\Commentary\\com.txt"))
return(Commentary)
close(readLines)
closeAllConnections()
}
我不知道这个函数出了什么问题。当我在R中运行这段代码时,它总是给我以下警告:
Warning message:
closing unused connection 5 ("C:\\Commentary\\com.txt")
发布于 2011-06-10 16:59:08
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)
然而,要编写您的函数,我可能会采取稍微不同的策略:
getCommentary <- function(filepath) {
con <- file(filepath)
on.exit(close(con))
Commentary <-readLines(con)
Commentary
}
它的用法如下,上面创建的文本文件作为示例文件进行读取
R> getCommentary("foo.txt")
[1] "foobar"
我使用了on.exit()
,这样一旦创建了con
,无论出于什么原因,如果函数终止,连接都将关闭。如果只在最后一行之前使用close(con)
语句,例如:
Commentary <-readLines(con)
close(con)
Commentary
}
该函数可能会在readLines()
调用时失败并终止,因此连接不会关闭。即使函数提前终止,on.exit()
也会安排关闭连接。
https://stackoverflow.com/questions/6304073
复制相似问题