簡體   English   中英

在R,Ubuntu 14.04 LTS,R版本3.2.4中的特定目錄中打開txt文件時出現的問題

[英]Issue in opening a txt file in a specific directory in R, Ubuntu 14.04 LTS, R version 3.2.4 Revised

嘗試通過read.table讀取文件夾中的txt文件時遇到一個非常奇怪的問題。 它可以識別文件的存在(我通過打印方法進行了調試),但是無法將文件讀入表中。 有人知道出什么問題了嗎? 我已經看過其他相關主題,但是找不到適合我問題的答案。 這是我的代碼:

path1 = "/home/yoda/Desktop/thesis/TullyFisher/Galac.RC_Dwarfs/TFRCHI/bins_29_04/7bins_TF/datasets/TFR/"
out.file<-""
file.names1 <- dir(path1, pattern =".txt")
listofdfs<-list()
for(i in 1:length(file.names1))
{
     print(file.names1[i])
     file <- read.table(file.names1[i])
     df<-data.frame(as.numeric(file[[1]]),as.numeric(file[[2]]),as.numeric(file[[3]]),as.numeric(file[[4]]))
     listofdfs[[i]]<-df
     #write.table(listofdfs[[i]],file=paste0("outliers_",file.names1[i],quote=F,row.names = F, col.names = F))
}

它返回:

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

它必須是文件路徑。 該目錄不是工作目錄,並且dir()僅返回文件名,而不返回完整路徑。 使用full.names參數應該可以解決此問題。 例如

dir("~/Desktop", full.names = T)

錯誤是因為您嘗試讀取的文件不在當前目錄中。 R總是嘗試從當前目錄讀取文件。

要知道您當前的目錄,請嘗試:

getwd()

它與您的path1不同。

因此,@ RS在上面提到過,請使用full.names。 請嘗試以下方法:

path1 = "/home/yoda/Desktop/thesis/TullyFisher/Galac.RC_Dwarfs/TFRCHI/bins_29_04/7bins_TF/datasets/TFR/"
out.file<-""
file.names1 <- dir(path1, pattern =".txt",full.names = T)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM