Select Page

How to Solve R Error in file(file, ifelse(append, ‘a’, ‘w’)) : cannot open the connection

by | Programming, R, Tips

This error occurs if you try to write to a file in a directory that was not found by the R interpreter. You can solve this error by creating the directory using dir.create() or removing the missing directory from the file save path. For example,

x <- c(rnorm(10))
write(x, file="vector.txt", sep=",")

This tutorial will go through how to solve this error with code examples.


Table of contents

Example

Consider an example of a data frame containing the names, salaries, and start dates of five employees for a fictional company.

# Create the data frame.

emp.data <- data.frame(

   emp_id = c (1:5), 

   emp_name = c("Terry","Julia","Ryu","Sean","Kirthika"),

   salary = c(623.3,515.2,611.0,729.0,843.25), 
   
   start_date = as.Date(c("2018-01-01", "2019-09-23", "2020-11-15", "2021-05-11",
      "2022-03-27")),

   stringsAsFactors = FALSE

)

# Print the data frame.			

print(emp.data) 
emp_id emp_name salary start_date
1      1    Terry 623.30 2018-01-01
2      2    Julia 515.20 2019-09-23
3      3      Ryu 611.00 2020-11-15
4      4     Sean 729.00 2021-05-11
5      5 Kirthika 843.25 2022-03-27

Next, we will try to save the data frame to a CSV using the write.table() function:

write.table(emp.data, file="accounts/salaries.csv", sep="\t", row.names = FALSE)

Let’s run the code to see what happens:

Error in file(file, ifelse(append, "a", "w")) : 
  cannot open the connection
In addition: Warning message:
In file(file, ifelse(append, "a", "w")) :
  cannot open file 'accounts/salaries.csv': No such file or directory

The error occurs because the directory “accounts” does not exist as a subdirectory within our working directory.

We can check if a directory exists using the dir.exists() function.

print(dir.exists("accounts"))
[1] FALSE

Solution

We can use the dir.create() function to create the subdirectory to write the file. Let’s look at the revised code:

# Create the data frame.

emp.data <- data.frame(

   emp_id = c (1:5), 

   emp_name = c("Terry","Julia","Ryu","Sean","Kirthika"),

   salary = c(623.3,515.2,611.0,729.0,843.25), 
   
   start_date = as.Date(c("2018-01-01", "2019-09-23", "2020-11-15", "2021-05-11",
      "2022-03-27")),

   stringsAsFactors = FALSE

)

# Create directory

dir.create("accounts/")

# Check the directory exists

print(dir.exists("accounts"))

# Write the data frame to file

write.table(emp.data, file="accounts/salaries.csv", sep="\t", row.names = FALSE)
[1] TRUE

Once we run the code the csv file can be found in the “accounts” subdirectory inside the working directory.

Summary

Congratulations on reading to the end of this tutorial!

For further reading on R-related errors, go to the articles: 

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!