In R, if you try to load a file that does not exist using load()
function, you will raise the error Error in readchar(con, 5l, usebytes = true) : cannot open the connection.
To solve this error you need to check that the file exists and that the spelling you used for the filename is correct.
This tutorial will go through the error and how to solve it with code examples.
Example
Let’s look at an example of a data frame with two columns.
dat1 <- data.frame(x=c("A", "B", "C", "D"), vals = c(2, 4, 6, 8)) dat1
x vals 1 A 2 2 B 4 3 C 6 4 D 8
Next, we will save the data frame to an R Data File (RDA).
save(dat1, "test1.rda")
Now in a new session, we will try to load the .RDA
file using load()
load("dat.rda")
Let’s run the code to see what happens:
Error in readChar(con, 5L, useBytes = TRUE) : cannot open the connection In addition: Warning message: In readChar(con, 5L, useBytes = TRUE) : cannot open compressed file 'dat.rda', probable reason 'No such file or directory'
The error occurs because the file dat.rda
does not exist in the directory.
Solution
We can check if the file exists and the correct name using list.files()
list.files()
"data.rda"
We can see that the file is called data.rda
not dat.rda
. Let’s try to load data.rda
into our program:
load("data.rda") dat1
Let’s run the code to see the result:
x vals 1 A 2 2 B 4 3 C 6 4 D 8
We successfully loaded the data frame into the program.
Summary
Congratulations on reading to the end of this tutorial!
For further reading on R related errors, go to the articles:
- How to Solve R Error: $ operator is invalid for atomic vectors
- How to Solve R Error in file(file, “rt”) cannot open the connection
- How to Solve R Error: plot.window(…): need finite ‘ylim’ values
Go to the online courses page on R to learn more about coding in R for data science and machine learning.
Have fun and happy researching!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.