I know that I can find file name from full file path in R, but is there a way to define the path to the file just from the file name? Think about such scenario: you store the data file in the cloud (e.g. Dropbox) so the path for this file is slightly different at your home: read.table("path/user1/data.dat")
and work: read.table("path/user2/data.dat")
. Therefore, every time you want to read.table()
you have to change one element of the path to match either you work or home path (on Mac OS X it's specifically the User
part of the path that you need to change). I was wondering whether it's possible to make R to automatically detect such change in the path (e.g. different User
) or detect the path to the file just from the name of this file.
Asked
Active
Viewed 1.2k times
2

Community
- 1
- 1

Geek On Acid
- 6,330
- 4
- 44
- 64
-
2Not really an answer, but the path to a home directory can be set as `"~/"`. In Windows this seems to path to `user\documents` which by default holds the dropbox folder and in linux to `user` which by default holds the dropbox folder. So for dropbox `read.table("~/Dropbox/...")` should work, I think. Should also work for Mac (as that is Unix). – Sacha Epskamp Dec 02 '11 at 11:53
-
@Sasha No, it won't work on Mac. Dropbox is held within `/Users/username/Dropbox/...`. – Geek On Acid Dec 02 '11 at 14:58
-
Yeah and `"~/"` should link to `/Users/username/` on Mac and Linux, not `/users`. sorry about that. – Sacha Epskamp Dec 02 '11 at 15:28
-
You're much better off learning how to use working directories than messing with fragile automated solutions. – hadley Dec 03 '11 at 12:48
1 Answers
6
You can access the environment variables with Sys.getenv()
.
Here is a short extract from the results on my machine:
Sys.getenv()
...
USERNAME
"Andrie"
USERPROFILE
"C:\\Users\\Andrie"
windir
"C:\\Windows"
You can extract individual elements by including the name of that element in the call:
> Sys.getenv("USERNAME")
[1] "Andrie"
If you can identify in these variables exactly what it is you need, you can then construct your file path using file.path
For more information on the environment variables, and some system-specific exceptions, see ?Sys.getenv

Andrie
- 176,377
- 47
- 447
- 496
-
excellent, thank you. On Mac this element in `Sys.getenv()` is either `USER` or `LOGNAME`. – Geek On Acid Dec 02 '11 at 14:55