error in file(file, “rt”) : cannot open the connection

Total
0
Shares

R throws error in file(file, “rt”) : cannot open the connection, when it’s not able to find the file in the provided path. This could happen either due to wrong path or current working directory is set incorrectly.

Consider this code –

directory <- ("./superhero")
list.files(directory)

This code will throw the error because we are saying that superhero is a directory and we want to list files within it. in R, you will need to let the system know that its a directory and not a file. This is done by suffixing the directory name with slash (/). Check this code –

directory <- ("./superhero/")
list.files(directory)

Another problem occurs due to setting of wrong working directory. It’s always best to provide an absolute path in setwd() function. Look at this code –

setwd('C:/Users/akash/Desktop')
data = read.csv("./superhero/avengers.csv")
data

In this example, I first set the current working directory using setwd() command. I consider my project to be on desktop so I used that path. Then in superhero folder I saved my avengers.csv file which I am reading.

If you are using backslash path like this – C:\Users\akash\Desktop, then you will need to escape it – C:\\Users\\akash\\Desktop. Try not to use spaces in path and if they are there then escape them too.

    Tweet this to help others