'Error in file(filename, "r", encoding = encoding) : cannot open the connection
I have an RScript file (let's call it main.r) which has a reference to another file, using the below code:
source("functions.R")
But, when I run the RScript file, it complains with the below error:
Error in file(filename, "r", encoding = encoding) :
cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
cannot open file 'functions.R': No such file or directory
I am sure, my main.R file is next to functions.R in the same directory.
I can call the functions.R in the Rmd (RMarkdown) file which exist in the same directory
Solution 1:[1]
In your case try to add setwd("path/to/project/") in main.R where path/to/project/ contains main.R.
Then you can source functions.R either directly by source("functions.R") if both files lie in the same directory or source("sub-folder/functions.R") if the latter file is contained in a sub-folder.
If you're not working on a RStudio project, chances are the working directory of main.R might be your home directory.
Solution 2:[2]
If the file you source ALSO uses source("...") to reference other files, you will get this same error.
For example:
- Your working directory is
getwd()".../projectA" - You have another file you want to reference from another R Project called
functions.R. So you try to source thissource(".../projectB/functions.R"). This results in the error. - It's because contained in the code of
functions.Rissource("helper_functions.R"). But your source is using the original path (e.g.,.../projectA/), not the project path offunctions.R(e.g.,.../projectB/)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Jeff Parker |
