Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Source function in R, error cannot find file - do I have to change working directory?

Tags:

r

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!

like image 914
Canovice Avatar asked Jan 09 '17 19:01

Canovice


People also ask

What to do when R says Cannot change working directory?

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.

What does Cannot change working directory mean in R?

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.

How do I set the working directory in R from source file?

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.


2 Answers

I added this before sourcing, it worked for me :

setwd(dirname(getwd()))
like image 180
Mnl Avatar answered Oct 28 '22 19:10

Mnl


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.

  1. Go to properties of your R software which is installed as below

  2. Find the Start in path: which is the path R pointing to so in source command use that path

like image 32
user9656334 Avatar answered Oct 28 '22 20:10

user9656334