2016-07-14 37 views
0

我想實現一個代碼到我的劇本,將我的計算機上創建一個新的文件夾,並保存圖到它,使用:如何覆蓋使用功能R中的計算機上的文件夾

daily <- "D:/Work/R/Daily" 
dir.create(daily) 
for (d in unique(data.air$yr_day)) { 
mypath <- file.path(daily, paste(name, d, ".png", sep = "")) 
png(filename = mypath, width = 963, height = 690) 
timePlot(subset(data.air, yr_day == d), 
     plot.type = "p", 
     y.relation = y.scale, 
     pollutant = c("co2.ppm", "o2.permeg", "apo"), 
     date.pad = TRUE, 
     pch = c(19,19,19), 
     cex = 0.2, 
     xlab = paste("Time of day in hours on", d), 
     ylab = "CO2, O2, and APO concentrations", 
     name.pol = c("CO2 (ppm)", "O2 (per meg)", "APO (per meg)"), 
     date.breaks = 24, 
     date.format = "%H:%M" 
) 
dev.off() 
} 

然而,第一次運行之後,每當我再次運行該代碼,該功能不會覆蓋舊的文件夾和情節在裏面,而不是返回此錯誤:

Warning message: 
In dir.create(daily) : 'D:\Summer Work with Andrew\R\Daily' already exists 

那麼,如何更改代碼,以便它每次我再次運行代碼時,都會用新的覆蓋舊的繪圖/文件夾?

謝謝

+0

你並不需要覆蓋的文件夾每次。您可以在頂部添加:'if(!file.exists(daily))dir.create(daily)'。這將創建'每日'文件夾,只有當它不存在。這些圖會自動覆蓋。 – ytk

+0

@ytk @ytk增加你的調整擺脫了警告信息,但是,它似乎沒有被覆蓋(我檢查了創建的日期,這是舊的日期) –

+1

測試目錄是否存在是什麼'dir.create '已經做到了。要看不到警告,請使用'dir.create(path,showWarnings = FALSE)'。如果你想刪除目錄中的所有內容,你可以在你調用'dir.create(dir)'之前解除(dir)'' – Ulrik

回答

1

我設法解決了這個問題,多虧了意見的建議。 爲了簡化將來使用的工作,我創建了一個新的功能,沒有工作的@Ulrik在上面的評論說:

make.dir <- function(fp) { 
if(!file.exists(fp)) { # If the folder does not exist, create a new one 
make.dir(dirname(fp)) 
dir.create(fp) 
} else { # If it existed, delete and replace with a new one 
unlink(fp, recursive = TRUE) 
dir.create(fp) 
    } 
}