You are on page 1of 2

File Handling in R Programming

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.

Syntax: file.create(“name of the file”)

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.

Syntax: write.table(x, file)


x: indicates the object that has to be written into the file & file: indicates the name of the file that has to be
written

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.

Syntax: file.rename(from, to)


from: indicates current file name or path & to: indicates new file name or path

Eg: file.rename("GFG.txt", "newGFG.txt") # Rename file GFG.txt to newGFG.txt

4) Check Existence of a File

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)

new.iris <- read.table(file = "GFG.txt") # Reading txt file

print(new.iris) # Print

6) List all Files

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)

list.files() # Show all files in current working directory

7) Copy a File

The file.copy() function in R helps to create a copy of specified file from console itself.

Syntax: file.copy(from, to)


from: indicates the file path that has to be copied & to: indicates the path where it has to be copied

file.copy("C:/Users/Utkarsh/Documents/newGFG.txt", "E:/") # Copying

list.files("E:/") # List the files in E:/ drive

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

list.files() # List files

You might also like