如何在R中使用setwd / getwd9(附示例)

1,499 阅读1分钟

每当你使用R时,你的环境总是被指向某个工作目录。

你可以在R中使用以下函数来获取工作目录和设置工作目录。

  • getwd()- 获取当前工作目录
  • setwd('Path/To/Some/Directory') - 设置当前工作目录

下面的例子展示了如何在实践中使用这些函数。

例1:获取工作目录

我们可以使用**getwd()**函数来显示R中的当前工作目录。

#display current working directory
getwd()

[1] "C:/Users/Bob/Desktop"

例2:设置工作目录

我们可以使用**setwd()**函数来设置工作目录到某个新的位置。

#set working directory
setwd('C:/Users/Bob/Documents')

然后,我们可以通过再次使用**getwd()**函数获取当前工作目录来验证工作目录是否已经改变。

#display current working directory
getwd()

"C:/Users/Bob/Documents"

例3:查看工作目录下的文件

一旦我们设置了工作目录,我们就可以使用list**.files()函数**来查看该目录下的文件名。

#view number of files in working directory
length(list.files())

[1] 147

#view first five file names in working directory
head(list.files())

"output.yml"  "analysis3.R"  "analysis3-1.R"  "testdoc.R"  "final_model2.Rmd" 

我们还可以使用**%in%**操作符来检查一个特定的文件是否位于我们当前的工作目录中。

#check if file 'analysis3.R' exists in working directory
'analysis3.R' %in% list.files()
[1] TRUE

一个TRUE的输出值表明特定的文件确实位于当前工作目录中。

其他资源

下面的教程解释了如何在R中执行其他常用功能。

如何在R中手动输入原始数据
如何将CSV文件导入R
如何将Excel文件导入R
如何在R中修复:无法改变工作目录

The postHow to Use setwd / getwd in R (With Examples)appeared first onStatology.