例子:
我的工作目录:
getwd() # [1] "D:/Example Directory"
与 dir function
path <- getwd() dir(path) # "1.R"
这个目录中唯一的文件是R文件 1.R . 我想把这个R文件复制10次。应该调用副本 2.R , 3.R , 4.R 等等。
1.R
2.R
3.R
4.R
问题:我怎样才能自动复制这个R文件?
你可以用 file.copy 需要原始文件名作为第一个参数并接受所需文件名向量作为第二个参数的函数。
file.copy
file.copy(dir(getwd()), paste0(2:10, ".R"))
PS:确保当前目录的开头只有一个文件。
或者你可以用一个安全的解决方案 list.files file.exists :
list.files
file.exists
nFiles <- 10 myFile <- list.files(pattern = "\\d.R") for(i in seq_len(nFiles)) { wantedFile <- sub("\\d", i, myFile) if (!file.exists(wantedFile)) { file.copy(myFile, wantedFile) } }