更改R中的主目录

时间:2014-06-06 02:29:34

标签: r

在R中,如果我使用命令

write.csv(res,"~/table1_n500.csv")

,然后结果保存在C:\Users\John Smith\Documents中。 但我希望它保存在C:\Users\John Smith\

我可以将此主目录(由〜标记引用)更改为C:\Users\John Smith\吗?

2 个答案:

答案 0 :(得分:1)

根据我的个人经验,我通常从文件导入数据(例如在目录C:\ Users \ John Smith \ DATA中)

然后我将工作目录设置为

setwd("C:/Users/John Smith/DATA")

虽然我想将输出文件保存在其他目录中,例如" C:\ Users \ John Smith"但不在数据文件夹中。

所以我将设置相对工作目录,如

setwd("../")

当您输入getwd()时 你会得到[1] "C:/Users/John Smith"

希望得到这个帮助。

答案 1 :(得分:0)

有两种方法可以解决这个问题。

1。)使用函数setwd()设置工作目录(或主目录)。所有save和read命令都将查找该工作目录中的文件。我只是谨慎地使用它,并且用于快速的小项目。

2.)更优选的方法是定义类似dataInputDir的变量,并使用函数file.path(dataInputDir, <your filename>)生成文件路径。优点是,如果您从(到)多个目录中读取(写入)数据,则可以更有效地执行此操作:

file.path(dataInputDir1, <your file or dir name>)
file.path(dataInputDir2, <your file or dir name>)
file.path(dataOutputDir1, <your file or dir name>)
file.path(dataOutputDir2, <your file or dir name>)

这种方法对于大型复杂项目非常方便,强烈建议使用。 如果您的程序要在Windows,Mac,Linux等多个平台上执行,这也很有用。您只需要在一个地方更改目录位置,其他所有内容都可以顺利运行。

此外,以下函数/句柄对于处理目录名称非常有用:

快速修复:

setwd("../") # setwd to parent folder of current working directory (getwd())

更强大:

setwd(dirname(dataInputDir)) # Setwd to parent folder of dataInputDir
相关问题