R語言:檔案操作
在批量處理資料時,通常需要對檔案或資料夾進行操作,下面將R語言中處理檔案和資料夾的常用函式整理一下。
1、工作路徑
getwd() 列出當前工作路徑;
setwd(dir) 設定工作路徑,引數dir是要設定的路徑。
2、列出目錄下檔案
函式list.files和dir用法完全一樣,可以列出路徑下所有檔案(包括目錄);函式list.dirs只列出路徑下所有目錄。
list.files(path =".", pattern = NULL, all.files = FALSE,
full.names = FALSE, recursive =FALSE,
ignore.case = FALSE, include.dirs =FALSE, no.. = FALSE)
dir(path =".", pattern = NULL, all.files = FALSE,
full.names = FALSE, recursive = FALSE,
ignore.case = FALSE, include.dirs = FALSE,no.. = FALSE)
list.dirs(path =".", full.names = TRUE, recursive = TRUE)
引數:
path
pattern 正則表示式,若pattern不為NULL,返回檔案(目錄)名滿足該正則表示式的檔案(目錄);
all.files 若為FALSE則不顯示隱藏檔案(目錄),若為TRUE則返回所有檔案(目錄);
full.names 若為FALSE則只返回檔案(目錄)名,若為TRUE則返回檔案(目錄)路徑;
recursive 若為FALSE則只返回該路徑的子級檔案(目錄),若為TRUE則返回所有子、孫檔案(目錄);
ignore.case 若為TRUE則在匹配pattern時不區分大小寫;
include.dirs 在recursive為TURE,即顯示所有子、孫檔案時,若include.dirs為FALSE則只列出最終端的檔名,而不列出中間層級的目錄名;
no.. 若為TRUE,則不顯示“.”和“..”。
3、新建目錄
dir.create用於新建目錄
dir.create(path, showWarnings = TRUE, recursive = FALSE,mode = "0777")
函式預設recursive為FALSE,即只新建path中的第一級子目錄,而當recursive為TRUE時可以新建多級子目錄。
值得注意的是,當目錄已存在時不會新建目錄覆蓋原先的目錄,此時如果showWarnings為TRUE,則會提醒該目錄已存在,為FALSE時不會提醒。
另外,引數mode是個Unix-alike引數。
4、複製
file.copy用於複製檔案
file.copy(from, to, overwrite = recursive, recursive = FALSE,
copy.mode = TRUE, copy.date = FALSE)
from是原始檔案(目錄)名,to是新檔案(目錄)名,二者可以是vector,但是長度需相同;
overwrite 若為TRUE,則檔案被覆蓋;
recursive 複製目錄時recursive需為TRUE;
copy.mode若為TRUE,permission bits一併複製過來;
copy.date若為TRUE,檔案日期一併複製過來。
5、刪除
函式unlink可以用來刪除檔案或目錄,函式file.remove可以用來刪除檔案。
unlink(x, recursive = FALSE, force = FALSE)
x是要刪除的檔案或目錄,可以是vector(即批量刪除);當刪除目錄時,recursive應為TRUE,表示目錄內檔案一併刪除。
6、重新命名
file.rename用於重新命名
file.rename(from, to)
from是原始檔案(目錄)名,to是新檔案(目錄)名,二者可以是vector,但是長度需相同。
7、檢視檔案是否存在
dir.exists(paths)
file.exists(paths)
引數paths可以是vector,即可以批量檢視檔案(目錄)是否存在。