File Handling in R Programming: Eg: File - Create ("GFG - TXT")
File Handling in R Programming: Eg: File - Create ("GFG - TXT")
In R Programming, handling of files such as reading and writing files can be done by using in-built functions
present in R base package.
1) Creating a File
Using file.create() function, a new file can be created from console. The function returns a TRUE logical value
if file is created otherwise, returns FALSE.
Eg: file.create("GFG.txt") # The file created can be seen in your working directory
2) Writing to a File
write.table() function in R programming is used to write an object to a file. This function is present in utils
package in R and writes data frame or matrix object to any type of file.
Eg: write.table(x = iris[1:10, ], file = "GFG.txt") # Write iris dataset # into the txt file
3) Renaming a File
The file.rename() function renames the file and return a logical value. This renames files but not directories.
A file exists or not in current working directory can be checked using file.exists() function. It returns TRUE
logical value if file exists, otherwise returns FALSE.
Syntax: file.exists(“name of the file that has to be searched in the current working directory”)
Eg: file.exists("GFG.txt") # Check for GFG.txt
5) Reading a File
Using read.table() function in R, files can be read and output is shown as data frame. This function helps in
analyzing the data frame for further computations.
Syntax: read.table(file)
print(new.iris) # Print
Using list.files() function, all files of specified path will be shown in the output. If path is not passed in
the function parameter, files present in current working directory is shown as output.
Syntax: list.files(path)
7) Copy a File
The file.copy() function in R helps to create a copy of specified file from console itself.
8) Create a Directory
The dir.create() function creates a directory in the path specified in the function parameter. If path is not
specified in function parameter, directory is created in current working directory.
Syntax: dir.create(path)
dir.create("GFG") # Without specifying the path, directory will be created in current working directory