在R中设置相对输出目录

时间:2016-07-11 11:45:31

标签: r

我有一个R脚本,它从多个xlsx文件中读取数据,将它们转换为数据帧,然后根据数据帧的行值在我的计算机的目录中创建文件夹。我已经在我的代码的开头设置了主目录:

choose.dir(getwd(), "Choose a suitable folder")

创建文件夹的输出目录,如:

pth <- "C:/Users/Dev/Desktop/test/"

我想在多台计算机上运行脚本,这意味着名为 pth 的输出目录并不总是相同。有没有办法设置相对输出路径,以便每次运行脚本时指定我希望结果的位置?我试过了

pth <- choose.dir(default = "", caption = "Choose the output path")

虽然会弹出一个对话窗口并选择所需的目录,但我看不到任何文件夹。

到目前为止,这是我的代码:

#choose working directory
choose.dir(getwd(), "Choose a suitable folder")

library(xlsx)
library(tcltk)

#get file names
f = list.files("./")

#read files
dat <- lapply(tk_choose.files(caption="Choose your files"), function(i) {
  x <- read.xlsx(i, sheetIndex = 1, sheetName = NULL, startRow = 24,
                 endRow = NULL, as.data.frame = TRUE, header = FALSE, Filters = Filters[c("xlsx")])
  #return columns with names and colors
  x <- x[, c(2, 5, 7, 9, 11, 13, 15, 17, 19), drop = FALSE]
  #return the data
  x
})

library(plyr)
df1 <- ldply(dat, data.frame) ## convert list into a dataframe

#remove NA's
complete.cases(df1)
x <- df1[complete.cases(df1),]
str(x)

#show specific rows
df1$X2 <- gsub("[[:punct:]]","-",df1$X2)
df <-df1[grepl("^[0-9]|^[a-zA-Z][0-9].*", df1$X2), ]
#print(df)

##pth <- "C:/Users/Dev/Desktop/test/"
pth = choose.dir(default = "", caption = "Choose the output path")

# Iteratate within each row of df
for(i in 1:nrow(df)){
  if (!file.exists(pth))
    # Create 1st path
    dir.create(paste0(pth , df$X2[i]), na.omit(df$X2[i]))
  # Create 2nd and 3rd paths
  dir.create(paste0(pth, df$X2[i], "/",df$X5[i]), na.omit(df$X2[i]))
  dir.create(paste0(pth, df$X2[i], "/",df$X7[i]), na.omit(df$X2[i]))
  dir.create(paste0(pth, df$X2[i], "/",df$X9[i]), na.omit(df$X2[i]))
  dir.create(paste0(pth,  df$X2[i], "/",df$X11[i]), na.omit(df$X2[i]))
  dir.create(paste0(pth,  df$X2[i], "/",df$X13[i]), na.omit(df$X2[i]))
  dir.create(paste0(pth,  df$X2[i], "/",df$X15[i]), na.omit(df$X2[i]))
  dir.create(paste0(pth,  df$X2[i], "/",df$X17[i]), na.omit(df$X2[i]))
  dir.create(paste0(pth,  df$X2[i], "/",df$X19[i]), na.omit(df$X2[i]))
}

1 个答案:

答案 0 :(得分:1)

您可以使用相对路径说明符来完成此操作。例如:

getwd()
[1] "C:/Users/Uwe/Documents/Rdevel/coverage"
setwd("../stackoverflow/")   # .. means go up one directory level
getwd()
[1] "C:/Users/Uwe/Documents/Rdevel/stackoverflow"
setwd("../..")   # go up two levels
getwd()
[1] "C:/Users/Uwe/Documents"

这也适用于unix。

BTW:.表示实际目录。所以,

getwd()
[1] "C:/Users/Uwe/Documents"
setwd("./Rdevel/")   # . denotes actual directory
getwd()
[1] "C:/Users/Uwe/Documents/Rdevel"

相当于

getwd()
[1] "C:/Users/Uwe/Documents"
setwd("Rdevel")
getwd()
[1] "C:/Users/Uwe/Documents/Rdevel"