楼主: Laplace_Yin
45672 17

[问答] R语言怎么获取当前文件所在文件夹 [推广有奖]

11
xiangxing98 发表于 2015-1-11 15:49:51
## --------------------------- System Setting Start ---------------------------
## 01. Choose Directory AND Set As Working Directory
WorkingDirectory <- choose.dir()
setwd(WorkingDirectory)
## FilePath <- file.choose(WorkingDirectory)
## FilePath <- file.choose(getwd())
## dir(getwd())
## 02. loading R Script and input data
source("MyRCode.R")
rawData <- read.csv(file.choose(getwd()), header = F, sep = ',')
## 03. Record Current Date Time
DateTime <- format(Sys.time(), "%Y-%m-%d %H-%M-%S")
## --------------------------- System Setting Ended ---------------------------

## -------------------------- File Name Module Start --------------------------
# get the file name from the choosen file
FilePath <- file.choose(WorkingDirectory)
# [1] "F:\\JMP-DOE-Statistics\\Statistics-R\\Code_Data_Notes\\
# Chapter01-Code_Answer_Notes.r"
# Split File Path 2 List By 2 Backslash \\
FilePathList <- strsplit(FilePath,"\\\\")
# get the number of elements from list File Path List
FilePathListLength <- length(FilePathList[[1]])
# get the last element that is the file name
FileName <- FilePathList[[1]][FilePathListLength]
sprintf("The File Name is: ")
sprintf("%s", FileName)

## -------------------------- File Name Module Ended --------------------------
已有 2 人评分经验 论坛币 收起 理由
李会超 + 20 热心帮助其他会员
admin_kefu + 50 热心帮助其他会员

总评分: 经验 + 20  论坛币 + 50   查看全部评分

12
17212937 发表于 2015-2-13 11:02:49
#我这样做的
previousWorkPath = setwd(choose.dir())  #选择你的文件所在的目录,如果事先知道路径也可以把choose.dir()改为绝对路径值

#这里写你的代码
#...
#代码结束
setwd(previousWorkPath )


已有 1 人评分论坛币 收起 理由
admin_kefu + 10 热心帮助其他会员

总评分: 论坛币 + 10   查看全部评分

13
jonwei 发表于 2015-8-30 17:38:56
  1. this.dir <- dirname(parent.frame(2)$ofile)
  2. setwd(this.dir)
复制代码
我只能说,写的人好牛啊


14
linzhjbtx 发表于 2018-7-24 11:38:37
jonwei 发表于 2015-8-30 17:38
我只能说,写的人好牛啊
能否解释下,这个运行有错误哦

15
kingzhu 发表于 2018-7-25 07:57:07
都是牛人,学习了

16
xiangxing98 发表于 2019-11-17 15:06:33
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
切记路径中不能有中文字符!
RStudio中设置当前源文件目录作为工作目录

17
xiangxing98 发表于 2019-11-17 15:07:45
RStudio中设置当前源文件目录作为工作目录为工作目录
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
切记路径中不能有中文字符!

18
hmy112233 学生认证  发表于 2021-9-28 08:31:33
xiangxing98 发表于 2019-11-17 15:07
RStudio中设置当前源文件目录作为工作目录为工作目录
setwd(dirname(rstudioapi::getActiveDocumentContex ...
亲测mac可用,路径中有中文字符也可正常运行!

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群
GMT+8, 2025-12-24 18:38