Home > Back-end >  Error in openning a file in R with two different method
Error in openning a file in R with two different method

Time:07-25

I have trouble opening a file in R with the following for loop :

#Counting the number of files in the folder
num_files <- length(list.files("C:/Users/Jane/Downloads/WantedFolder"))
num_files

#File extraction from the folder
a<-list.files("C:/Users/Jane/Downloads/Folder")

for (i in 1:num_files){
    g<-a[i]
    data1<-read.table(g)
    head(data1)
}

To me it should be working as the classic read.table :

data1<-read.table("C:/Users/Jane/Downloads/WantedFolder/WantedFile.txt")

I got the following error and don't understand why since I've checked the directory several times and it is working for the "classic" read.table

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

What is wrong ?

CodePudding user response:

It depends on your working directory, which you can check using getwd(). list.files only returns the names of the files in a folder, not their full path. Based on the error, it seems like you are trying to open a file called "wantedfile.txt" in your current working directory. To avoid R assuming your current working directory, you can specify the absolute path like so:

path <- "C:/Users/Jane/Downloads/Folder"
a <- list.files(path)
a <- file.path(path, a)

This pastes the absolute path of the wanted folder to the file names returned by list.files-

  •  Tags:  
  • r
  • Related