Open In App
Related Articles

Reading contents of a Text File in R Programming – read.table() Function

Like Article
Save Article
Report issue

The read.table() 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 read.table().

It returns the data in the form of a table.

Syntax: read.table(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 


# R program to read a text file
# Get content into a data frame
data <- read.table("TextFileExample.txt",
                    header = FALSE, sep = " ")
# Printing content of Text File



   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

Example 2: Reading data from a different directory 


# R program to read a text file
# Reading data from another directory
x<-read.table("D://Data//myfile.txt", header = FALSE)
# print x



   V1 V2 V3
1 100 a1 b1
2 200 a2 b2
3 300 a3 b3

R’s read.table() function offers a robust and adaptable method for reading text file contents into data frames, facilitating effective data analysis and manipulation. we can easily import text data into R and make the most of all of R’s data processing options by following the instructions provided in this article. Learning how to read text files in R will greatly improve your capacity to draw insightful conclusions from your data, regardless of whether you are working with big or little data sets.


Q.1: Can we specify the column names while reading the text file?

Yes, we can specify column names while reading the text file using the col.names parameter in the 
read.table() function. 

Q.2: How can we skip header lines or ignore specific rows while reading the text file?

If your text file contains header lines or rows that you want to skip while reading,you can use the
skip parameter in the read.table() function. Specify the number of lines to skip as the value of 
the skip parameter. For example, to skip the first two lines, you can use.

Q.3: How to handle missing or incomplete values while reading?

The read.table() function provides the na.strings parameter to handle missing or incomplete values.
we can specify the character strings that should be treated as missing values using this parameter. 

Last Updated : 01 Aug, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads