Define the file path from the file name in R

梦想的初衷 提交于 2019-12-24 01:19:57

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/8355762/define-the-file-path-from-the-file-name-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!