[R] How to automatically set R to read the files from a specific location
Jeff Newmiller
jdnewm|| @end|ng |rom dcn@d@v|@@c@@u@
Thu Mar 3 00:27:58 CET 2022
1) make a working directory. Put all related files (including your R file(s) in that directory or in subdirectories.
2) Set your working directory as "current" before starting R. If you or anyone who wants to use your code does this, no actions will be needed in the script to "change" the directory. This is straightforward at the shell using "cd", and GUI file managers will normally do this automatically for you if you "open" a file using an action that triggers starting R from there. RStudio uses the .Rproj file to serve this purpose, so if you use RStudio then always create a Project for each separate "project" you work on.
3) Use relative paths in your code. You can access a csv file in your working directory as "filename.csv" or in a subdirectory data_dir of your working directory using "data_dir/filename.csv".
4) Send a zip archive of your "project" directory/contents to the recipient so the relative locations of files is maintained. Or consider using GitHub (e.g. [1]) to share and track changes.
Note that sometimes you may not want to include the data in your project directory because switching data sets will be common. In that case you cannot achieve this goal, but you can use a global variable to specify your data directory path and use file.path( dtadir, fname ) wherever your specify a file for input. The recipient then only needs to alter one line of your code.
[1] https://happygitwithr.com/
On March 2, 2022 2:54:43 PM PST, Paul Bernal <paulbernal07 using gmail.com> wrote:
>Dear friends,
>
>I am working on an assignment using R, and I would like to set my R code so
>that R automatically recognizes where the files that need to be read are
>without having to use the absolute path?
>The idea is that when I send my .R script and my professor receives it, he
>can just execute the code without running into any issues.
>
>Thanks, beforehand, for your valuable feedback.
>
>Cheers,
>Paul
>
> [[alternative HTML version deleted]]
>
>______________________________________________
>R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.
--
Sent from my phone. Please excuse my brevity.
More information about the R-help
mailing list