从文件夹中读取文件,尽管索引正确,但我收到 "Error in file(file, "rt") : cannot open the connection" 错误

Reading files from a folder and despite indexing correctly, I receive a "Error in file(file, "rt") : cannot open the connection" error

我正在尝试从文件夹中读取文件。 我设置了工作目录和目标文件夹。

setwd("F://directory/SimulationOutputs/folder - Copy/")
spwfolder <- ("F:/directory/SimulationOutputs/folder - Copy/spws/")
spws <- list.files(spwfolder)

完成这一步后,我检查它是否正确:

 spws[1]
[1] "Cambridge2018_136.txt"

接下来,我要读取第一个文件:

spw<-read.table(spws[1], sep=";", row.names=NULL, skip = 8, fill = TRUE, 
header=TRUE, stringsAsFactors = FALSE)

我收到这条消息:

Error in file(file, "rt") : cannot open the connection In addition: Warning message: In file(file, "rt") : cannot open file 'Cambridge2018_136.txt': No such file or directory

我做错了什么? 提前致谢!

您将工作目录设置为 /folder - Copy/ 但您的文件位于 /folder - Copy/spws/.

或者,您可以将 list.filesfull.names=TRUE 一起使用,这样 spws 将包含文件的完整路径,这样您的工作目录设置在哪里就无关紧要了。