The readLines() function in R can be used to read some or all text lines from a connection object.
This function uses the following syntax:
readLines(con, n=-1L)
where:
- con: A connection object or character string
- n: The maximum number of lines to read. Default is to read all lines.
The following examples show how to use this function in practice with the following text file called some_data.txt:
Example 1: Use readLines() to Read All Lines from Text File
Suppose the text file is saved in my Documents folder on my computer.
I can use the following readLines() function to read each line from this text file:
#read every line from some_data.txt
readLines("C:/Users/Bob/Documents/some_data.txt")
[1] "The first line of the file" "The second line of the file"
[3] "The third line of the file" "The fourth line of the file"
[5] "The fifth line of the file" "The sixth line of the file"
The text file contains 6 lines, so the readLines() function produces a character vector of length 6.
If I’d like, I can save the lines from the text file in a data frame instead:
#read every line from some_data.txt my_data #create data frame df = data.frame(values=my_data) #view data frame df values 1 The first line of the file 2 The second line of the file 3 The third line of the file 4 The fourth line of the file 5 The fifth line of the file 6 The sixth line of the file
The result is a data frame with one column and six rows.
Example 2: Use readLines() to Read First N Lines from Text File
Once again suppose the text file is saved in my Documents folder on my computer.
I can use the following readLines() function with the n argument to read only the first n lines from this text file:
#read first 4 lines from some_data.txt
readLines("C:/Users/Bob/Documents/some_data.txt", n=4)
[1] "The first line of the file" "The second line of the file"
[3] "The third line of the file" "The fourth line of the file"
The readLines() function produces a character vector of length 4.
I can also use brackets to access a specific line from this text file.
For example, I can use the following code to access just the second line from the character vector:
#read first 4 lines from some_data.txt my_data 4) #display second line only my_data[2] [1] "The second line of the file"
Additional Resources
The following tutorials explain how to import other types of files in R:
How to Use read.table in R
How to Import CSV Files into R
How to Import Excel Files into R