How can others who run my R program read a file(eg: csv) used in my R code without having to change the working directory in setwd()?
-
Where does the data come from? If you want to find files relative to your R script, maybe look at the [here package](https://here.r-lib.org/). Or are you using RStudio? If so, consider using RStudio projects. Read more about [project oriented workflows](https://www.tidyverse.org/blog/2017/12/workflow-vs-script/) – MrFlick Aug 06 '21 at 18:39
-
Are you on Windows? – DeBARtha Aug 08 '21 at 03:55
2 Answers
I will suggest you use the here()
function in the here
package in your code like this:
library(here)
Data1 <- read_csv(here("test_data.csv"))

- 1,381
- 1
- 10
- 28
read.csv
has a file
argument and if I were to quote from the inbuilt R
help about file
:
If it does not contain an absolute path, the file name is relative to the current working directory,
getwd()
.
So, providing the absolute path of the file inside the file
argument solves this problem.
In Windows
Suppose your file name is test.csv
and it's located in D:\files\test_folder
(you can get the location of any file from its properties in Windows)
For reading this file you run:
df<-read.csv('D:\\files\\test_folder\\test.csv')
or
df<-read.csv('D:/files/test_folder/test.csv')
Suggested reading: Why \\
instead of \
and Paths in programming languages
Haven't used R
in Linux but maybe Getting a file path in Linux might help
Read from web
Just type in the web address of the dataset in the file
attribute. Try:
df<-read.csv('https://raw.githubusercontent.com/AdiPersonalWorks/Random/master/student_scores%20-%20student_scores.csv')
Note: This link contains a list of 25 students with their study hours and marks. I myself used this dataset for one of my earlier tasks and its perfectly safe

- 460
- 6
- 17