Reading contents of a Text File in R Programming read.table() Function (original) (raw)
Last Updated : 25 Apr, 2025
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 `
data <- read.table("TextFileExample.txt", 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
**Explanation: The file "TextFileExample.txt" is read from the current directory. The header = FALSE argument states that there is no header row in the file, and sep = " " says that columns are separated by spaces.
**Example 2: Reading data from a different directory
R `
R program to read a text file
Reading data from another directory
x<-read.table("D://Data//myfile.txt", header = FALSE)
print x
print(x)
`
**Output:
V1 V2 V3
1 100 a1 b1
2 200 a2 b2
3 300 a3 b3
**Reading contents of a Text File in R Programming - read.table() Function - FAQs
**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.
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.
**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.