创建子目录并存储文件

时间:2019-04-15 05:19:05

标签: r

如何在脚本中设置路径,所以不必导航到该文件夹​​即可运行.csv文件,又如何从创建的png文件中创建文件夹示例“ code_coverage_png”?

.csv文件位于名为“ codecov”的文件夹中。

library(tidyverse)
library(ggplot2)






setwd(paste(getwd(),"codecov",sep="/"))
csv_list = list.files(pattern="*.csv")
print(csv_list)

png_csv_path= (paste(getwd(),"codecov_png",sep="/"))
dir.create(png_csv_path)
print(png_csv_path)


for(i in 1:length(csv_list)){

  data_frame <-read.csv(csv_list[i], header =  TRUE)
  data_frame$dayDifference <- as.numeric(gsub("[^[:digit:]]","",data_frame$dayDifference))
  #if(names(data_frame) %in% "dayDifference"){data_frame$dayDifference <- as.numeric(gsub("[^[:digit:]]","",data_frame$dayDifference))}
  print(data_frame$dayDifference)
  print(csv_list[i])
  gg <- ggplot(data = data_frame , mapping = aes(x = covpercent, y = dayDifference)) +
    geom_point() +
    scale_y_continuous(limits=c(0,max(data_frame$dayDifference))) +
    labs(x = "Code coverage",
         y = "Number of days between releases",
         title = basename(csv_list[i]) # just file name, not whole path
    )

  #ggsave(filename = sub('\\.csv$', '.png', csv_list[i]), device = "png", plot = gg) # change file extension to indicate output format
  #message(file.path(png_csv_path, sub('\\.csv$', '.png', basename(csv_list[i]))))
  ggsave(filename = file.path(png_csv_path, sub('\\.csv$', '.png', basename(csv_list[i])), device ="png", plot = gg))
}

1 个答案:

答案 0 :(得分:1)

只需在path中设置list.files()并返回full.names

csv_list = list.files(path="/full/path/to/codecov/", pattern="*.csv", full.names=T)

如果csv文件位于该路径的子目录中,请同时设置recursive=T

csv_list = list.files(path="/full/path/to/codecov/", pattern="*.csv", full.names=T, recursive=T)

然后创建输出目录:

img_path="/full/path/to/codecov/code_coverage_png"
dir.create(img_path)

最后将输出文件的路径设置为新目录:

ggsave(filename = file.path(img_path, sub('\\.csv$', '.jpeg', basename(csv_list[i])), plot = gg) # change file extension to indicate output format