Translate

Friday, 30 January 2015

Directory & File Management

Managing directory from R becomes handy when automating batch processes, and helps with managing disk spaces when extracting and manipulating large volumes of data.


To check contents of the current (working) directory:

dir()



To obtain more information about the directory or files:

file.info(dir())  
  
file.info("home/document/folder_name")   



To set working directory:

setwd("home/document/folder_name")



To identify path to the current (working) directory:

getwd()



To create a new directory (you can only specify the file name if you are creating the new directory within the working directory):

dir.create("home/document/folder_name")
   

To create a new file:

file.create("FILE.txt")  



To create a temporary file or directory:

tempfile()  
  


To remove all files in a directory:

unlink("home/document/folder_name/*")



To delete a directory (you need to ensure that the directory you are trying to delete is not set as the working directory):

unlink("home/document/folder_name",recursive=TRUE)




To remove a file:

file.remove("home/document/folder_name/file_name.txt")



To check if a certain file exists:

file.exists("home/document/folder_name/file_name.txt")



To select files in the directory using wildcard:

Sys.glob("M*")  



To copy a file from one directory to another:

file.copy("home/document/folder_name/file_name.txt","home/document/folder_name2/file_name.txt")




To copy a file and replace a existing file with the same name:

file.copy("home/document/folder_name/file_name.txt","home/document/folder_name2/file_name.txt",overwrite=TRUE)


To copy multiple files from one directory to another:

file.copy(FILES,paste("home/document/folder_name2",FILES,sep="/"))



To change name of a file:

file.rename("home/document/folder_name/file_name.txt","home/document/folder_name/file_name2.txt")


To append files:

file.append("home/document/folder_name/file_name1.txt","home/document/folder_name/file_name2.txt","home/document/folder_name/file_name3.txt")

To compress a file into zip file:

zip("home/document/folder_name/zip_file_name.zip","home/document/folder_name/file_name.txt")



To extract files from compressed zip files:

unzip("home/document/folder_name/zip_file_name.zip",exdir="home/document/folder_name2")



To extract files from tar archive:

untar("home/document/folder_name/tar_file_name.tar",exdir="home/document/folder_name2")



To import gz files into R:
 

dat <- read.table(gzfile("path/file/txt.gz"), sep=", ", header = TRUE)  

  
  







1 comment: