从R中的文件名定义文件路径 [英] Define the file path from the file name in R

查看:346
本文介绍了从R中的文件名定义文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以从完整文件中查找文件名R 中的路径,但是有没有一种方法可以仅通过文件名来定义文件的路径?考虑一下这样的情况:您将数据文件存储在云中(例如Dropbox),因此该文件的路径在您的家庭read.table("path/user1/data.dat")和工作地点read.table("path/user2/data.dat")略有不同.因此,每次要read.table()时,都必须更改路径的一个元素以匹配您的工作路径或家庭路径(在Mac OS X上,具体来说就是您需要更改的路径的User部分).我想知道是否可以让R自动检测路径中的此类更改(例如,不同的User)或仅从该文件的名称检测文件的路径.

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.

推荐答案

您可以使用Sys.getenv()访问环境变量.

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"


如果您可以在这些变量中准确地确定所需的内容,则可以使用file.path

有关环境变量和某些系统特定异常的更多信息,请参见?Sys.getenv

For more information on the environment variables, and some system-specific exceptions, see ?Sys.getenv

这篇关于从R中的文件名定义文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆