This may be a duplicate, but I couldn't find a solution when I searched online and it's an issue that has been bugging me for some time. I am given a zip file with 2 .R files, I download the zip and move the .R files into a directory on my computer, let's say "/Users/Home/StatisticsStuff/LearningR/".
My two files are Stats1.R and Stats2.R, and the first line of code in Stats1.R is:
source(Stats2.R)
and I get the following error message:
> source("Stats2.R")
Error in file(filename, "r", encoding = encoding) : cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) : cannot open file 'Stats2.R': No such file or directory
when i run getwd(), to see which working directory I'm in, I get:
getwd()
"/Users/Home"
It seems like it would be a pain to have to change working directories in order to source files? Is there something I'm doing wrong here with regards to what I'm expecting from the source() function? Do I have to put a line in my code above everything else using setwd("whatever the correct wd is").
Any thoughts appreciated!
Fixing this problem is simply a matter of eliminating the “~/” reference from your script. Because the setwd() function is the set working directory function, you can use it to set the current directory in your code. All you need to do is set it to the file path folder you are looking for.
Unfortunately, the RStudio console returns the error message “cannot change working directory”. The reason for this is that the directory we are trying to access does not exist. We might have specified the folder name wrong, or the path before the folder name is not existing.
Step 1) Click on the Session tab. Step 2) Click on Set Working Directory > To Source File Location. Afterwards, you working directory will be changed to the location of your source file.
I added this before sourcing, it worked for me :
setwd(dirname(getwd()))
first write this command list.files() then you can know which location of your R is pointing or see the below image that R-Pointing to then write the source command with correct path. it will be executed.
follow these steps to see the R pointing path.
Go to properties of your R software which is installed as below
Find the Start in path: which is the path R pointing to so in source command use that path
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With