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

In this tutorial you’ll learn how to fix the message “Error in file(file, “rt”) : cannot open the connection” in the R programming language.

One common error you may encounter in R is:

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

This error occurs when you try to read a CSV file in R, but the file or directory name you are trying to access does not exist.

How to Reproduce the Error

Suppose I have a CSV file called data.csv saved in the following location:

C:\Users\Joach\Desktop\data.csv

And suppose the CSV file contains the following data:

team, points, assists
'A', 78, 12
'B', 85, 20
'C', 93, 23
'D', 90, 8
'E', 91, 14

Suppose I use the following syntax to read in this CSV file into R:

#attempt to read in CSV file
df <- read.csv('data.csv')

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

I receive an error because this file doesn’t exist in the current working directory.

How to Fix the Error

I can use the getwd() function to actually find the working directory I’m in:

#display current directory
getwd()

[1] "C:/Users/Bob/Documents"

Since my CSV file is located on my desktop, I need to change the working directory using setwd() and then use read.csv() to read in the file:

#set current directory
setwd('C:\\Users\\Bob\\Desktop')

#read in CSV file
df <- read.csv('data.csv', header=TRUE, stringsAsFactors=FALSE)

#view data
df

  team points assists
1    A     78      12
2    B     85      20
3    C     93      23
4    D     90       8
5    E     91      14

It worked!

Another way to import the CSV without setting the working directory would be to specify the entire file path in R when importing:

#read in CSV file using entire file path
df <- read.csv('C:\\Users\\Bob\\Desktop\\data.csv', header=TRUE, stringsAsFactors=FALSE)

#view data
df

  team points assists
1    A     78      12
2    B     85      20
3    C     93      23
4    D     90       8
5    E     91      14

Related Articles

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Categories