File reading in R
One of the important formats to store a file is in a text file. R provides
various methods that one can read data from a text file.
[Link](): This method is used for reading “tab-separated value”
files (“.txt”). By default, point (“.”) is used as decimal point.
Syntax: [Link](file, header = TRUE, sep = "\t", dec = ".", ...)
Parameters:
file: the path to the file containing the data to be read into R.
header: a logical value. If TRUE, [Link]() assumes that your file
has a header row, so row 1 is the name of each column. If that’s not
the case, you can add the argument header = FALSE.
sep: the field separator character. “\t” is used for a tab-delimited file.
dec: the character used in the file for decimal points.
Example:
# R program reading a text file
# Read a text file using [Link]()
myData = [Link]("[Link]", header = FALSE)
print(myData)
[Link](): In R it’s also possible to choose a file interactively using
the function [Link](), and if you’re a beginner in R programming
then this method is very useful for you.
Example:
# R program reading a text file using [Link]()
myFile = [Link]([Link](), header = FALSE)
# If you use the code above in RStudio
# you will be asked to choose a file
print(myFile)
read_tsv(): This method is also used for to read a tab separated (“\t”)
values by using the help of readr package.
Syntax: read_tsv(file, col_names = TRUE)
Parameters:
file: the path to the file containing the data to be read into R.
col_names: Either TRUE, FALSE, or a character vector specifying
column names. If TRUE, the first row of the input will be used as the
column names.
Example:
# R program to read text file
# using readr package
# Import the readr library
library(readr)
# Use read_tsv() to read text file
myData = read_tsv("[Link]", col_names = FALSE)
print(myData)
Reading one line at a time
read_lines(): This method is used for the reading line of your own choice
whether it's one or two or ten lines at a time. To use this method we have
to import reader package.
Syntax: read_lines(file, skip = 0, n_max = -1L)
Parameters:
file: file path
skip: Number of lines to skip before reading data
n_max: Numbers of lines to read. If n is -1, all lines in the file will be
read.
Example:
# R program to read one line at a time
# Import the readr library
library(readr)
# read_lines() to read one line at a time
myData = read_lines("[Link]", n_max = 1)
print(myData)
# read_lines() to read two line at a time
myData = read_lines("[Link]", n_max = 2)
print(myData)
Output:
[1] "A computer science portal for geeks."
[1] "A computer science portal for geeks."
[2] "Geeksforgeeks is founded by Sandeep Jain Sir."
[Link](): [Link]() is used for reading “comma separated value” files
(“.csv”). In this also the data will be imported as a data frame.
Syntax: [Link](file, header = TRUE, sep = ",", dec = ".", ...)
Example:
# R program to read a file in table format
# Using read.csv2()
myData = read.csv2("[Link]")
print(myData)
R - Writing to Files
Writing Data to CSV files in R Programming Language
CSV stands for Comma Separated Values. These files are used to handle
a large amount of statistical data. Following is the syntax to write to a CSV
file:
Syntax:
[Link](my_data, file = "my_data.csv")
write.csv2(my_data, file = "my_data.csv")
Writing Data to text files
Text files are commonly used in almost every application in our day-to-day
life as a step for the "Paperless World". Well, writing to .txt files is very
similar to that of the CSV files. Following is the syntax to write to a text
file:
Syntax:
[Link](my_data, file = "my_data.txt", sep = "")
Writing Data to Excel files
To write data to excel we need to install the package known as "xlsx
package", it is basically a java based solution for reading, writing, and
committing changes to excel files. It can be installed as follows:
[Link]("xlsx")
and can be loaded and General syntax of using it is:
library("xlsx")
[Link](my_data, file = "[Link]",
sheetName = "my_data", append = FALSE).
Reading the whole file
read_file(): This method is used for reading the whole file. To use this
method we have to import reader package.
Syntax: read_lines(file)
file: the file path
Example:
# R program to read the whole file
# Import the readr library
library(readr)
# read_file() to read the whole file
myData = read_file("[Link]")
print(myData)
Reading contents of a Text File in R
Programming - [Link]() Function
Last Updated : 25 Apr, 2025
The [Link]() function in R can be used to read a text file's contents. A
versatile and often used function for reading tabular data from different file
formats, including text files, is [Link](). It returns the data in the form
of a table.
Syntax:
[Link](filename, header = FALSE, sep = "")
Parameters:
header: represents if the file contains header row or not
sep: represents the delimiter value used in file
Example 1: Reading data from the same directory
data <- [Link]("[Link]",
header = FALSE, sep = " ")
# Printing content of Text File
print(data)
Output:
V1 V2 V3
1 100 A a
2 200 B b
3 300 C c
4 400 D d
5 500 E e
6 600 F f
readr
The goal of readr is to provide a fast and friendly way to read tabular data into R. The most
important functions are:
Read delimited files: read_delim(), read_csv(), read_tsv(), read_csv2().
Read fixed width files: read_fwf(), read_table().
Read lines: read_lines().
Read whole file: read_file().
Re-parse existing data frame: type_convert().
#[Link]("readr")
library(readr)
dput: Write an Object to a File or
Recreate it
Description
Writes an ASCII text representation of an R object to a file or connection, or uses one to
recreate the object.
Usage
dput(x, file = "",
control = c("keepNA", "keepInteger", "niceNames",
"showAttributes"))
dget(file, [Link] = FALSE)
Arguments
an object.
file
either a character string naming a file or a connection. "" indicates output to the console.
control
character vector indicating deparsing options. See .deparseOpts for their description.
[Link]
logical: should the source formatting be retained when parsing functions, if possible?
Value
For dput, the first argument invisibly.
For dget, the object created.
Details
dput opens file and deparses the object x into that file. The object name is not written
(unlike dump). If x is a function the associated environment is stripped. Hence scoping
information can be lost.
Deparsing an object is difficult, and not always possible. With the
default control, dput() attempts to deparse in a way that is readable, but for more complex
or unusual objects (see dump), not likely to be parsed as identical to the original.
Use control = "all" for the most complete deparsing; use control = NULL for the
simplest deparsing, not even including attributes.
dput will warn if fewer characters were written to a file than expected, which may indicate a
full or corrupt file system.
To display saved source rather than deparsing the internal representation
include "useSource" in control. R currently saves source only for function definitions. If
you do not care about source representation (e.g., for a data object), for speed
set options([Link] = FALSE) when calling source.
xx <- pi^(1:3)
dput(xx)
dput(xx, control = "digits17")
dput(xx, control = "hexNumeric")
dput(xx, fil); dget(fil)
--
dump: Text Representations of R
Objects
Description
This function takes a vector of names of R objects and produces text representations of the
objects on a file or connection. A dump file can usually be sourced into another R session.
Usage
dump(list, file = "dumpdata.R", append = FALSE,
control = "all", envir = [Link](), evaluate = TRUE)
Arguments
list
character vector. The names of one or more R objects to be dumped.
file
either a character string naming a file or a connection. "" indicates output to the console.
append
if TRUE and file is a character string, output will be appended to file; otherwise, it will
overwrite the contents of file.
control
character vector indicating deparsing options. See .deparseOpts for their description.
envir
the environment to search for objects.
evaluate
logical. Should promises be evaluated?
Value
An invisible character vector containing the names of the objects which were dumped.
Details
If some of the objects named do not exist (in scope), they are omitted, with a warning.
If file is a file and no objects exist then no file is created.
sourceing may not produce an identical copy of dumped objects. A warning is issued if it is
likely that problems will arise, for example when dumping exotic or complex objects (see the
Note).
dump will also warn if fewer characters were written to a file than expected, which may
indicate a full or corrupt file system.
A dump file can be sourced into another R (or perhaps S) session, but the function save is
designed to be used for transporting R data, and will work with R objects that dump does not
handle. For maximal reproducibility use control = c("all", "hexNumeric").
To produce a more
x <- 1; y <- 1:10
fil <- tempfile(fileext=".Rdmped")
dump(ls(pattern = '^[xyz]'), fil)
print(.[Link])
unlink(fil)
#}
Binary File
A binary file is a file that contains information stored only in form of bits and
bytes.(0s and 1s). They are not human readable as the bytes in it translate to
characters and symbols which contain many other non-printable characters.
Attempting to read a binary file using any text editor will show characters like
Ø and ð.
The binary file has to be read by specific programs to be useable. For
example, the binary file of a Microsoft Word program can be read to a human
readable form only by the Word program. Which indicates that, besides the
human readable text, there is a lot more information like formatting of
characters and page numbers etc., which are also stored along with
alphanumeric characters. And finally a binary file is a continuous sequence of
bytes. The line break we see in a text file is a character joining first line to the
next.
Sometimes, the data generated by other programs are required to be
processed by R as a binary file. Also R is required to create binary files which
can be shared with other programs.
R has two functions WriteBin() and readBin() to create and read binary
files.
Syntax
writeBin(object, con)
readBin(con, what, n )
Following is the description of the parameters used −
con is the connection object to read or write the binary file.
object is the binary file which to be written.
what is the mode like character, integer etc. representing the bytes to be
read.
n is the number of bytes to read from the binary file.
Example
We consider the R inbuilt data "mtcars". First we create a csv file from it and
convert it to a binary file and store it as a OS file. Next we read this binary file
created into R.
Writing the Binary File
We read the data frame "mtcars" as a csv file and then write it as a binary file
to the OS.
# Read the "mtcars" data frame as a csv file and store only the columns
"cyl", "am" and "gear".
[Link](mtcars, file = "[Link]",[Link] = FALSE, na = "",
[Link] = TRUE, sep = ",")
# Store 5 records from the csv file as a new data frame.
[Link] <- [Link]("[Link]",sep = ",",header = TRUE,nrows = 5)
# Create a connection object to write the binary file using mode "wb".
[Link] = file("/web/com/[Link]", "wb")
# Write the column names of the data frame to the connection object.
writeBin(colnames([Link]), [Link])
# Write the records in each of the column to the file.
writeBin(c([Link]$cyl,[Link]$am,[Link]$gear),
[Link])
# Close the file for writing so that it can be read by other program.
close([Link])
Reading the Binary File
The binary file created above stores all the data as continuous bytes. So we
will read it by choosing appropriate values of column names as well as the
column values.
# Create a connection object to read the file in binary mode using "rb".
[Link] <- file("/web/com/[Link]", "rb")
# First read the column names. n = 3 as we have 3 columns.
[Link] <- readBin([Link], character(), n = 3)
# Next read the column values. n = 18 as we have 3 column names and 15
values.
[Link] <- file("/web/com/[Link]", "rb")
bindata <- readBin([Link], integer(), n = 18)
# Print the data.
print(bindata)
# Read the values from 4th byte to 8th byte which represents "cyl".
cyldata = bindata[4:8]
print(cyldata)
# Read the values form 9th byte to 13th byte which represents "am".
amdata = bindata[9:13]
print(amdata)
# Read the values form 9th byte to 13th byte which represents "gear".
geardata = bindata[14:18]
print(geardata)
# Combine all the read values to a dat frame.
finaldata = cbind(cyldata, amdata, geardata)
colnames(finaldata) = [Link]
print(finaldata)
When we execute the above code, it produces the following result and chart
−
[1] 7108963 1728081249 7496037 6 6
4
[7] 6 8 1 1 1
0
[13] 0 4 4 4 3
3
[1] 6 6 4 6 8
[1] 1 1 1 0 0
[1] 4 4 4 3 3
cyl am gear
[1,] 6 1 4
[2,] 6 1 4
[3,] 4 1 4
[4,] 6 0 3
[5,] 8 0 3
As we can se