R getwd() 和 setwd() 函数 - 工作目录
R getwd() 函数用于获取当前工作目录,setwd() 用于设置工作目录。
工作目录是指 R 读取和写入文件时的默认路径。
两个函数语法格式如下:
getwd() setwd(dir)
参数说明:
dir 新的工作目录路径(字符串)。
实例
# 获取当前工作目录
current_dir <- getwd()
print(paste("当前工作目录:", current_dir))
# 查看目录内容
print("目录文件列表:")
print(list.files())
# 设置工作目录(示例)
# setwd("/Users/username/projects/runoob")
# 查看 R 的安装目录
print(paste("R 安装目录(R.home):", R.home()))
current_dir <- getwd()
print(paste("当前工作目录:", current_dir))
# 查看目录内容
print("目录文件列表:")
print(list.files())
# 设置工作目录(示例)
# setwd("/Users/username/projects/runoob")
# 查看 R 的安装目录
print(paste("R 安装目录(R.home):", R.home()))
执行以上代码会显示当前的 R 工作目录和文件列表。
在读取或写入文件时,如果只提供文件名(不包含路径),R 会在当前工作目录下寻找文件。为确保代码可移植,建议先设置正确的工作目录。

R 语言实例