Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error in openning a file in R with two different method

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading